1

Have this code (below) and am trying to display the text at the click of a button in React.js.

Heres the code:

class App extends Component{

render(){ 
  alert=()=>{return(<h1>Hi</h1>)}
  return(<div className="App">
    <button onClick={this.alert}>Enter</button>
  </div>);

}}

export default App;

Any ideas why it's not working...?

2
  • this refers to the class App. But the alert function you declared is inside the render method and so it is not a child of App class. So this won't work here. Remove this and try again Commented Oct 6, 2019 at 13:25
  • You are returning the rendered function component to onClick. Commented Oct 6, 2019 at 13:28

2 Answers 2

7

If you want to display it in an alert window, you need to call a function to trigger the window.

class App extends Component{

  onButtonClickHandler = () => {
    window.alert('Hi')
  };

  render(){ 
    return(<div className="App">
      <button onClick={this.onButtonClickHandler}>Enter</button>
    </div>);

  }
}

However, if you need to show the message in your render, you can use a state to manage that.

class App extends Component{
  state = {
    showMessage: false
  }
  onButtonClickHandler = () => {
   this.setState({showMessage: true});
  };

  render(){ 
    return(<div className="App">
     {this.state.showMessage && <p>Hi</p>}
      <button onClick={this.onButtonClickHandler}>Enter</button>
    </div>);

  }
}

Source code:

Edit dank-bush-edxbl

If you need to toggle the text on button click, you just need to update the onButtonClickHandler function to this.setState({ showMessage: !this.state.showMessage });.

Sign up to request clarification or add additional context in comments.

1 Comment

Need the text not in a popup
1

It won't display as like that. Here you are calling alert function and returning some JSX. How react will know where to render?. Do it like below.

class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
    render: false
}
this.alertHi = this.alertHi.bind(this);
}

alertHi() {
 this.setState({render: !this.state.render});
}

render() {
  return(
  <div className="App">
    <button onClick={this.alertHi}>Enter</button>
    {this.state.render && <h1>Hi</h1>}
  </div>
  );
 }
}

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.