11

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.

2
  • Probably you're chasing an anti-pattern and didn't understand the react way of thinking. Commented Nov 23, 2016 at 18:02
  • That comment by Inanc cracked me up. Commented Aug 17, 2018 at 11:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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'/>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.