5

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

1 Answer 1

10

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.

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

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.