-1

I have two separate components, which don't have a simple parent-child relationship.

ComponentFolderA 
|
ButtonComponent 

ComponentFolderB
|
BannerComponent

I want to setState when the user clicks on the button and send that value to the BannerComponent

What's the best way to get around this?

helpmepie
  • 244
  • 1
  • 6
  • 19

2 Answers2

2

In functional components, you can create a state in a parent component for both ButtonComponent and BannerComponent. Then do as the following example,

const Parent = () => {
    const [sampleState, setSampleState] = useState(null);

    return (
      <>
          <BannerComponent sampleState={sampleState} />
          <ButtonComponent setSampleState={setSampleState} />
      </>
    )
}

Then you can access the setSampleState as a prop inside the ButtonComponent.

Also, check this out Best practice way to set state from one component to another in React and you can use a state manager (Context API, Redux)

1

Keep state in the parent and send the state setting function down to your Button.

const Parent = () => {
  const [myState, setMyState] = useState(false);
  
  return (
    <>
      <BannerComponent myState={myState} />
      <ComponentWithButton setMyState={setMyState} />
    </>
  )
}

const ComponentWithButton = props => {
  return (
    <Button onClick={() => props.setMyState(true)} />
  )
}