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>
);
}
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).