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.

2
  • is this what you're looking for: stackoverflow.com/questions/24502898/…. Commented Nov 13, 2018 at 17:59
  • thank you for your information, but this is not the answer, this is not about modifying the existing div. Commented Nov 15, 2018 at 14:44

1 Answer 1

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

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

3 Comments

thank you for your information, maybe i did not describe correctly, so it should be something like this: <div id="example">example</div> <div id="root"></div>, so how can i hide and show the first "example" in the class that "root" has ?
why would you need React then ? Just do some: document.querySelector('#example').style.display = 'none';
Thank you so much ^_^, i find out how to do it from your tip.

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.