Reputation: 22580
I have a Reactjs render method 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 state variable but the changeMyVariable()
function runs twice.
Upvotes: 11
Views: 80071
Reputation: 4793
Although you can set local variables in the render, the use of props
is recommended for better modifiability.
So, you first 'declare' the property in the component:
class ExampleComponent extends React.Component {
static propTypes = {
myVariable: React.PropTypes.string.isRequired,
};
static defaultProps = {
myVariable: 'Default Value'
};
And then, you render this prop
at the ExampleComponent
render method:
render() {
return (
<div>{this.props.myVariable}</div>
);
}
To use this prop
when you render ExampleComponent
:
render() {
<ExampleComponent myVariable='example'/>
}
Upvotes: 2
Reputation: 15642
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).
Upvotes: 33