1

Is it possible to use react to show and hide an existing div element by id?

For example, I want use react to have this <div id="example">this is example</div> show and hide by button click and this element is not created by react.

Jacob Tomlinson
  • 3,341
  • 2
  • 31
  • 62
fong lee
  • 89
  • 2
  • 7
  • is this what you're looking for: https://stackoverflow.com/questions/24502898/show-or-hide-element-in-react. – Luis Osta Nov 13 '18 at 17:59
  • thank you for your information, but this is not the answer, this is not about modifying the existing div. – fong lee Nov 15 '18 at 14:44

1 Answers1

2

First you need to understand React's philosophy. I strongly suggest you read the official React tutorial: https://reactjs.org/tutorial/tutorial.html. In this case you would like to appear and disappear a div, this can be accomplished by changing internal state of a React Component. Then you need to create a function that is bound to the context of the instance of the Component. For example:

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: true,
    };
  }

  toggle() {
    const { open } = this.state;
    this.setState({
      open: !open,
    });
  }

  render() {
    const { open } = this.state;
    return (
      <main>
        <button onClick={this.toggle.bind(this)}>{open ? 'Hide' : 'Show'}</button>
        {open && <div id="example"><h1>this is example</h1></div>}
      </main>
    );
  }
}

Here's a codepen: https://codepen.io/anon/pen/PxWdZK?editors=1010

giwiro
  • 336
  • 2
  • 8
  • thank you for your information, maybe i did not describe correctly, so it should be something like this:
    example
    , so how can i hide and show the first "example" in the class that "root" has ?
    – fong lee Nov 15 '18 at 14:47
  • why would you need React then ? Just do some: `document.querySelector('#example').style.display = 'none';` – giwiro Nov 15 '18 at 17:08
  • 1
    Thank you so much ^_^, i find out how to do it from your tip. – fong lee Nov 23 '18 at 18:10