Reputation: 108
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
Upvotes: 3
Views: 2379
Reputation: 1908
What you have looks OK. But do you have a <Button>
component? If not, lowercase the "b" and use html's <button>
.
const Parent = () => {
const [state, setState] = React.useState(false);
const toggleState = () => setState(prevState => !prevState)
return (
<div>
<p>Parent State: {String(state)}</p>
<Child toggleState={toggleState}/>
</div>
);
};
const Child = ({toggleState}) => {
return <button onClick={toggleState}>Child Button</button>;
};
ReactDOM.render(<Parent />, document.getElementById("root"));
<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 id="root"></div>
Upvotes: 0
Reputation: 1213
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>
}
Upvotes: 3
Reputation: 371168
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>
Upvotes: 1