Home > OS >  How to call functions in same level components in reactjs?
How to call functions in same level components in reactjs?

Time:12-02

My root Component is App.js. It has many child components. But i have declare functions in child component and i need to access those function in equal level component in react js. [enter image description here][1]

this are the components hierarchy. i need to pass function from custom player to playbutton component [1]: https://i.stack.imgur.com/XpEt1.png

CodePudding user response:

Handle the state of the game in App.js. In their (custom player and playbutton component) parent. Pass the state function to them as props and handle the state there. Ex:

Function App () {
const [SomeState, setSomeState] = setState()
Return
<>
<Button setSomeState={setSomeState}><\Button>
<Button2 setSomeState={setSomeState}><\Button2>
<\>
}

Those buttons handle the same state.

CodePudding user response:

visit this site: https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component

You can pass state values to a child component as a prop, but you can also pass functions directly to the child component like this:

<ChildComponent
    // The child component will access using actionName
    actionName={this.actual_action_name}
/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

actionName is the name of the props that can be accessed by the child component. Once you trigger an action or pass the data from the child component, the same action's name will be accessed using this.props.action_name.

Let’s look at a simple example of passing the action to the child component.

<MyChildComponent
    onSubmitData={this.onSubmitData}
/>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related