Passing data to sibling components with react hooks?

Viewed 20156

I want to pass a variable username from sibling1 component to sibling2 component and display it there.

Sibling1 component:

const sibling1 = ({ usernameData }) => {
   // I want to pass the username value I get from input to sibling2 component
  const [username, setUsername] = useState(""); 

  const handleChange = event => {
    setUsername(event.target.value);
  };

  return (
    <Form.Input
        icon='user'
        iconPosition='left'
        label='Username'
        onChange={handleChange}
      />
    <Button content='Login' onClick={handleClick} />
  )
}

export default sibling1;

Sibling2 component:

export default function sibling2() {
  return (
    <h1> Here is where i want to display it </h1>
  )
}
3 Answers

You will need to handle your userName in the parent of your siblings. then you can just pass setUsername to your sibling1, and userName to your sibling2. When sibling1 use setUsername, it will update your parent state and re-render your sibling2 (Because the prop is edited).

Here what it looks like :

const App = () => {
  const [username, setUsername] = useState('Default username');
  return (
    <>
      <Sibling1 setUsername={setUsername} />
      <Sibling2 username={username} />
    </>
  )
}

const Sibling2 = ({username}) => {
  return <h1> Helo {username}</h1>;
}

const Sibling1 = ({setUsername}) => {
  return <button onClick={setUsername}>Set username</button>;
}

In parent of these two components create a context where you will store a value and value setter (the best would be from useState). So, it will look like this:

export const Context = React.createContext({ value: null, setValue: () => {} });

export const ParentComponent = () => {
 const [value, setValue] = useState(null);

 return (
  <Context.Provider value={{value, setValue}}>
   <Sibling1 />
   <Sibling2 />
  </Context.Provider>
 );

Then in siblings you are using it like this:

const Sibling1 = () => {
 const {setValue} = useContext(Context);

 const handleChange = event => {
  setValue(event.target.value);
 };
 // rest of code here
}

const Sibling2 = () => {
 const {value} = useContext(Context);

 return <h1>{value}</h1>;
}
Related