N
N
Nikolai2022-02-03 18:39:02
React
Nikolai, 2022-02-03 18:39:02

How to pass the state of a child component?

I have a child component whose state is passed to the parent via props

<button onClick={()=>props.changeOn()} "> </button>

The parent component receives it
const CenterSide = (props) =>
{
    const [IsOn,SetTop]=useState(false)
    const reverse= function (){
      if(IsOn==false){
          SetTop(true)
      }
      else {
         SetTop(false)

      };
    };

    return <div  ">
        <Nav  changeOn={reverse}/>
    </div>
}

But how to pass the state above from this parent component? without events like onClick()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2022-02-03
@Aetae

What for?
Everything goes from top to bottom and nothing else.
Either events, or context, or global storage like redux. But in any case, it must be set in advance.

A
Arslan Abaev, 2022-02-05
@ADDtvb

You can throw a callback function that returns the state from the child element to the parent, but this way the code becomes difficult to understand, and the abuse of such callbacks will lead to spaghetti code, as a result, you yourself will get confused, so use the Context better , but if you need this approach, here is the section from official docks and also the article , yes, the article is a bit out of date since there is an example on class components, but the approach will be clear, I figured out how to do it myself two years ago using this article)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question