Is it possible to change the value from a useState from inside the child component?
Parent:
const [state, setState] = useState(false);
return <Child func={() => setState(true)}/>
Child:
return <Button onClick={props.func}> Click me to set the state </Button>
It doesn't work this way, is there any way it could work? Thank you
You can do something like this
//PARENT
export default function Parent({}) {
const [state, setState] = useState(false);
function setParentValue(value){
setState(value)
}
return <Child setValue={setParentValue} />
}
//CHILD
export default function Child({setValue}) {
function buttonHandler(){
setValue('value')
}
return <Button onClick={buttonHandler}> Click me to set the state </Button>
}
That should work, as long as you also provide a way to look at the changed stateful value:
const { useState } = React;
const App = () => {
const [state, setState] = useState(false);
return (
<div>
State: {String(state)}
<Child func={() => setState(true)}/>
</div>
);
};
const Child = (props) => {
return <button onClick={props.func}> Click me to set the state </button>;
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With