'When I click on a link, how can I change the status of another component?
When I click on a button, it redirects me to another component (#2) where there are two states and according to which state it shows one content or another. The default state of the component(#2) is true and what I need to know how to do is that clicking on the button of the component(#1) changes the state to false.
This is for a ReactJs app, im using function components, hooks, no class components
Thats the button code:
<Link to="/register">
<button className="btn btn-success btnVerde">
</button>
</Link>
Thats the component#2:
const [state, setState] = React.useState(true);
{state && <div1......../>}
{!state && <div2......./>}
I expect to click on the button in component#1, it redirecto to component#2 how default state is true, and change it to false
Solution 1:[1]
Thx to @rcoro that is how I solve the problem component#1:
const change = () => props.changingState(false);
<Link to="/register"><button onClick={change}className="btnPink">
{t("talents_btnReserve")}
</button>
</Link>
component#2:
const showTalentRegister = () => setState(true);
const showCompanyRegister = () => setState(false);
useEffect(() => {
if(props.booleanState){
showCompanyRegister()
}
else {
showTalentRegister()
}
}, []);
Solution 2:[2]
you could handle the state in the component1, and in your onClick call setState and update the value with the oposite, eg:
<button onClick={() => setState({state: !state})}>Click</button>
and receive the value as a prop in component2, eg:
const Component2 = ({showCustom}) => {
if(showCustom) {
return <span> Custom </span>;
}
return <span>No Custom</span>;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Raul |
Solution 2 | Martijn Pieters |