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.
To render a Javascript expression in JSX, all you need to do is surround the expression in curly braces, like so: var Hello = React. createClass({ render: function() { return <div>Hello, { targetOfGreeting }! </div>; } });
If you use var outside of a function, it belongs to the global scope. If you use var inside of a function, it belongs to that function. If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block. var has a function scope, not a block scope.
Therefore, JSX is designed as a statically-typed language. All the values and variables have a static type and you can only assign a correctly-typed value to a variable.
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).
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'/>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With