0

I have a Stackblitz here

I'm simply trying to update the useState in one component from another component.

Its sort of working here but doesn't work at all in my app

The app.tsx is like

import * as React from 'react';
import Child from './Child';
import './style.css';

const App = () => {
  const [value, setValue] = React.useState('Red');

  return (
    <div>
      <div>{value}</div>
      <div>
        <Child onNameChange={setValue} />
      </div>
    </div>
  );
};

export default App;

And the child component like

import * as React from 'react';
import './style.css';

const Child = ({ onNameChange }) => {
  const handleInputChange = React.useCallback(() => {
    onNameChange('blue');
  }, [onNameChange]);

  return (
    <div>
      <form onSubmit={handleInputChange}>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
};

export default Child;

The problems here are it keeps reloading after the button is pressed.

And in App.tsx it errors on <Child onNameChange={setValue} /> with 'Child' cannot be used as a JSX component. Its return type 'void' is not a valid JSX element.

Can anyone explain how to get this working without these mistakes

lomine
  • 873
  • 5
  • 20
  • 36
  • Does this answer your question? [Stop form refreshing page on submit](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) – Konrad May 09 '23 at 19:17
  • This is not a react-specific problem. HTML form just reloads the page by default – Konrad May 09 '23 at 19:18
  • 1
    yeah sorry I forgot the `e.preventDefault();` – lomine May 09 '23 at 19:25

1 Answers1

0

this is because of the default behavior of the <form> element, It makes a GET request, the value of the form inputs will be the url query parameters (in your case there is no input so you only see the ? )

to solve this you can add this line to prevent this default behavior:

  const handleInputChange = React.useCallback(
    (e) => {
      e.preventDefault();
      onNameChange('blue');
    },
    [onNameChange]
  );