MMrj MMrj - 9 days ago 6
React JSX Question

Use componentDidMount variables from event functions

Im trying to access a variable created in the componentDidMount method. Whats the best way to do it?

componentDidMount() {
var x = "hello";
}

bye() {
x = "bye";
}

render(){
return (<div onClick={this.bye}>)
}

Answer

Use React's state for this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { x: "" };
    this.bye = this.bye.bind(this);
  }
  
  componentDidMount() {
    this.setState({ x: "hello" });
  }

  bye() {
    this.setState({ x: "bye" });
  }

  render(){
    return (<div onClick={this.bye}>{this.state.x}</div>)
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

Comments