Spy Spy - 26 days ago 11
Javascript Question

Update javascript variable on html after event- Reactjs

I am working on JSX and I have the following issue

JS

var results ="";
results = value that changes;


HTML

<div className="content" dangerouslySetInnerHTML={{__html: results}}></div>


I have the variable results that changes when a button is pressed. Originally the value is "" and after the event it becomes another string. I want to display the new string every time the button is pressed. Any suggestions?

Answer

You should add that variable to the state of your component. Firstly, add

getInitialState() {
  return { value : "initialValue" };
}

Or if using ECMA6,

constructor(props) {
  super(props);
  this.state = { value : "initialValue" };
}

When you want to change it, call

this.setState({ value : "newValue" });

And on the render method, use:

render() {
  return <div className="content" dangerouslySetInnerHTML={{__html: this.state.value}} />
}

Or something like that. Then when your state changes, react will redraw it, calling render again.

BTW, you should avoid dangerouslySetInnerHTML if possible. If you want, you can comment more about what you are doing to see if there are alternatives.