bier hier bier hier - 16 days ago 5
React JSX Question

How to set variable in render with reactjs?

I have a reactjs rendermethod and I am trying to set a variable through a function, it looks like this(you guessed it , does not work):

render() {
let myVariable=''

//this function changes/sets myVariable
this.changeMyVariable()

return (
<div>{myVariable}</div>
);
}


How can I set a variable that is used in my render through another function , something like the example above. I also tried to use a statevariable but the changeVariable function runs twice.

Answer
render() {
    // assuming 'changeMyVariable' returns a value
    const myVariable = this.changeMyVariable();

    return (
        <div>{myVariable}</div>
    );
}

Actually you can invoke the function inside your JSX itself:

<div>{this.changeMyVariable()}</div>.

Note: If the output of this.changeMyVariable() never changes based on new props, it is better to compute the value outside render (avoid re-calculating when component re-renders).