Hello. I've just started to learn props and states. Still learning. I'm trying to create a Button that changes the content of the other file.
Here's my Button.jsx that will be imported in Main.js
// Button.jsx
export default class Button extends React.Component {
constructor(props) {
super(props);
this.state = {isOn: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const x = this.state.isOn ? false : true;
this.setState({isOn: x})
}
render() {
return(
<button type="button" onClick={this.handleClick}>{JSON.stringify(this.state.isOn)}</button>
);
}
}
It's working. When I click on the button it toggles true and false .
Now I want to change the content of Main.js so that it shows "Hello" when it's true, and "Bye" when it's false. I want to do it with if else but it's not working with Button.state.isOn . I don't know how to do it.
// Main.js
render() {
const x = Button.state.isOn;
if (x) {
var txt = "Hello";
} else {
var txt = "Bye";
}
return (
<div>
<Button />
<span>{txt}</span>
</div>
);
}
How do I access the state of the Button ?
Maybe something like this might work for your case.
// Button.jsx
const Button = (props)=> (
<button type="button" onClick={props.handleClick}>{JSON.stringify(props.txt)}</button>
);
export default Button;
state = { isOn: false };
handleClick() {
this.setState({isOn: !this.state.isOn})
}
render() {
const { isOn } = this.state;
return (
<div>
<Button
txt={this.state.isOn},
handleClick={this.handleClick}
/>
<span>{isOn ? "Hello" : "Bye"}</span>
</div>
);
}
You don't. The state is limited to the component so you can't access it from the parent. A way to solve this would be to pass a function from parent into button and then the button can call that function with "isOn" as parameter and notifies the parent about a change. the parent can render the matching text. Important is here that the function is "bound" to the parent component.
If you create a sandbox on codesandbox.io or similar site then code suggestions could make things easier :)
Sebastian
I'll tell this to you the easy way, have you heard of HOC? Give it a read, and then come back to this answer. The state cannot be accessed from parent to child, it is always the other way round. It is like a water fall. State trickles down from the top and gets filtered the way down. This is the principle on which redux works by implementing it on a global scale. All you need to get this thing working is shift the state of the button to the parent state, create a function to change this state and pass it down to the button using props. Now, you can access the state in your parent component.
class Main extends Component{ constructor(props){ super(props); this.state = { isButtonOn: false, } } toggleButton = () => { this.setState((prevState)=>( { ...prevState, isButton: !prevState.isButtonOn, } ) ) } render(){ return ( <div> <div> {this.state.isOn?'Hello': 'Bye'} <div> <Button toggleButton={this.toggleButton} isOn={this.state.isOn}/> </div> ) } }