madhur
madhur

Reputation: 1001

use of variable inside render function of react component

I am learning React and came across a doubt, there are two codes in which variables used by render method in component are declared at different places, my doubt is why one works and other doesn't.

import React from 'react';
import ReactDOM from 'reactDOM';

const myVar = 'hello';

class myComponent extends React.Component {
    render () {
       return <h1>{myVar}</h1>;
    }
}

ReactDOM(
    <myComponent />,
    document.getElementById('app')
);

This works, means I am able to access global variable in render method.

But take this case which does not work

import React from 'react';
import ReactDOM from 'reactDOM';

class myComponent extends React.Component {
    const myVar = 'hello';

    render () {
       return <h1>{this.myVar}</h1>;
    }
}

ReactDOM(
    <myComponent />,
    document.getElementById('app')
);

I am confused here, can somebody explain this behavior

Upvotes: 5

Views: 4739

Answers (1)

illiteratewriter
illiteratewriter

Reputation: 4323

inside the class you don't define variables. You just have to write myVar='hello' not const myVar='hello'

Properties specified in a class definition are assigned the same attributes as if they appeared in an object literal.

Upvotes: 10

Related Questions