Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 657
madhur Avatar asked Dec 30 '17 09:12

madhur


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

What does render component inside React component do?

A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic. Libraries that use render props include React Router, Downshift and Formik.

Can we write function inside render?

That said, it's perfectly fine to declare functions inside a render method or more commonly these days a functional component. There are hooks like useCallback that can help with performance but 99% of the time it's not an issue.

How do you use variables in JSX?

Embedding Expressions in JSX In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces: const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>; You can put any valid JavaScript expression inside the curly braces in JSX.


1 Answers

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.

like image 146
illiteratewriter Avatar answered Sep 23 '22 23:09

illiteratewriter