Search code examples
reactjsonclickreact-propssetstatebuttonclick

Send state/props to another component in React with onClick


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?


Solution

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