React Node In State Keep Remember Props
Solution 1:
You are trying to access the state from App component in your Menu component.
State is local to that component and can't be accessed outside, if you would like to access the state outside the component you can refer to the useContext hook implementation.
https://reactjs.org/docs/hooks-reference.html#usecontext
Reason you are seeing 0 in the Active state is that is the default value of useState.
Solution 2:
You need to pass key to your menu component.
Whenever there is change in props, the component has to re-render with new props.
Refer this artcile from their official docs - https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key
Change I made is passing state as key to Menu component
const {useState} = React;
functionMenu({ items }) {
const [activeItem, setActiveItem] = useState(items[0]);
return (
<div>
{items}
<hr /><span>Active Item:</span>
{activeItem}
</div>
);
}
functionApp() {
const [state, setState] = useState(0);
console.log(state);
constonSelectItem = () => {
console.log("🐞: onSelectItem -> currentState", state);
};
const items = ["FirstItem", "SecondItem"].map(item => {
return (
<buttonkey={item}onClick={() => onSelectItem()}>
{item}
</button>
);
});
return (
<divclassName="App"><Menuitems={items}key={state}/><hr /><buttononClick={() => setState(prevState => prevState + 1)}>Change State</button></div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
<divid="app"></div><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><divid="react"></div>
Post a Comment for "React Node In State Keep Remember Props"