Spy Spy - 4 months ago 34
Javascript Question

Update javascript variable on html after event- Reactjs

I am working on JSX and I have the following issue


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


<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?


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

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

Or if using ECMA6,

constructor(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.