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
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>; } });
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With