最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing data to sibling components with react hooks? - Stack Overflow

programmeradmin1浏览0评论

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>
  )
}

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>
  )
}
Share Improve this question edited Jan 2, 2022 at 22:19 Emile Bergeron 17.4k5 gold badges84 silver badges131 bronze badges asked May 16, 2020 at 12:08 gospecomid12gospecomid12 1,0123 gold badges14 silver badges27 bronze badges 3
  • Is sibling2 called from sibling1? If so, you can just pass props. Or else you need to store in-app state and get from there. – Byrisetti Hemanth Commented May 16, 2020 at 12:14
  • @QuentinGrisel we don't know if he was downvoter ;) (btw wasn't me) I suspect some answerers do serial downvoting sometimes if they get a downvote which ain't healthy – Giorgi Moniava Commented May 16, 2020 at 12:29
  • @giorgim That's right, i thought about it after. But the advide is still valid. And i meant nothing bad by saying that, it's just unproductive – Quentin Grisel Commented May 16, 2020 at 12:31
Add a comment  | 

3 Answers 3

Reset to default 36

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>;
}

best way: React Context + hooks

you can use React Context. take a look at this example:

https://codesandbox.io/s/react-context-api-example-0ghhy

发布评论

评论列表(0)

  1. 暂无评论