The app works, but when I click the button nothing happens. I'm experimenting with buttons and I at least want to get a button to be able to affect the markup on the page.
class Add extends Component {
state = { }
clickme(){
<h2>hello</h2>
}
render() {
return (
<>
<Title />
<button type="button" onClick={this.clickme}>Add task</button>
</>
);
}
}
export default Add;
CodePudding user response:
Your function is not returning anything. You can use state and use clickme to update the state when the button is clicked
class Add extends Component {
state = { waiting:true, title:"" }
clickme(){
this.setState({ title: "Hello", waiting : false});
}
render() {
return (
<>
<h2>{this.state.waiting?"Waiting For Click...":this.state.title}</h2>
<button type="button" onClick={this.clickme}>Add task</button>
</>
);
}
}
export default Add;
CodePudding user response:
You need to return the component from the function. Either turn clickme() into an arrow function, which implicitly returns, or add a return statement (might have to wrap it in some brackets, not sure). Also, where do you expect the "hello" to render exactly?
P.S. Have you tried using functional instead of class components? That's been the recommended approach by the React team and community for a few years now.
class Add extends Component {
state = { }
clickme(){
return <h2>hello</h2>;
}
render() {
return (
<>
<Title />
<button type="button" onClick={this.clickme}>Add task</button>
</>
);
}
}
export default Add;
