How to render element on click of button: ReactJS

前端 未结 1 1347
时光说笑
时光说笑 2020-12-02 02:33

I am trying to render a paragraph as soon as the you click the button.

Here is my code.

import React, { Component } from \'react\';

class App exte         


        
1条回答
  •  情话喂你
    2020-12-02 03:10

    This is not the correct way because createText is a event handler it will not render the element, what you need is "Conditional rendering of elements".

    Check Docs for more details Conditional Rendering.

    Steps:

    1- Use a state variable with initial value false.

    2- Onclick of button update the value to true.

    3- Use that state value for conditional rendering.

    Working Code:

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          isShow: false
        }
        this.createText = this.createText.bind(this);
      }
    
    
      createText() {
        this.setState({ isShow: true }) 
      }
    
    
      render() {
        return (
          
    {this.state.isShow &&

    Hello World!!!

    }
    ); } } ReactDOM.render(, document.getElementById('app'))
    
    
    
    

    0 讨论(0)
提交回复
热议问题