Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set variable in render with reactjs?

Tags:

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.

like image 303
bier hier Avatar asked Nov 23 '16 10:11

bier hier


People also ask

How do you render variables in React?

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

Can we use VAR in React?

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.

Can JSX be assign to a variable?

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.


2 Answers

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

like image 90
yadhu Avatar answered Sep 30 '22 05:09

yadhu


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'/>
}
like image 24
otorrillas Avatar answered Sep 30 '22 06:09

otorrillas