use of variable inside render function of react component - javascript

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

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.

Related

difference between rfc and rfce in Reactjs

I am new in Reactjs and I want to know what is the difference between "react functional component"
and "react functional component export"?
Here is react functional component code
import React from 'react'
export default function Test() {
return (
<div>Test</div>
)
}
Here is "react functional component export"
import React from 'react'
function Test() {
return (
<div>Test</div>
)
}
export default Test
I want to add more context to your question: I suppose your question comes from the different snippets rfc and rfce of ES7+ React/Redux/React-Native snippets extension in VScode.
Two both cases do the same thing. The differences are the syntax of export. It's not particular to ReactJS but about JavaScript.
1st case: you use export directly before the declaration function line.
2nd case: you declare a function first and later use export with the function's name at the bottom of your code.
I'm used to using 2nd case.
You can read more about export syntax variant + named export vs. default export in this link
You mean the difference between Functional Components And Class Components?
The functions you have shared are the same, both are React Functional Component
React Class Components: is a class component requires you to extend from React Component and create a render function which returns a React element.
example:
import React from 'react'
export default class Test extends React.Component {
render () {
console.log(this.props)
return <div>Test</div>
}
}
React Functional Components: is just a plain JavaScript pure function that accepts props as an argument and returns a React element(JSX)
example:
import React from 'react'
export default function Test(props) {
console.log(props)
return (
<div>Test</div>
)
}

Returning Code from a TypeScript Module in React

I am trying to create a simple page which two main parts: Menu and Guide. In my App,tsx, I have:
import React from 'react';
import Guide from './Guide/Guide';
import './App.css';
function App() {
return (
<Guide />
);
}
export default App;
This is fine.
But, in the ./Guide/Guide.tsx, I have:
import React, { Component } from "react";
import Menu from "./Menu/Menu";
export default class Guide extends Component {
constructor(props: {}) {
super(props);
}
return (
<Menu />
);
}
Menu.tsx:
import React, { Component } from "react";
export default class Menu extends Component {
return (
<h1>Test</h1>
);
};
However I'm getting the error 'return', which lacks return-type annotation, implicitly has an 'any' return type..
What's going on here?
You can probably tell I'm very new to React and TypeScript!
In class component (such as your Guide and Menu components), you render some HTML code inside the render function. Insinde functional components (such as your App component), you render some HTML code inside the return function. Here you are mixing those 2 different syntax, that is why you are getting this error.
In order to fix this, simply replace your return function in the Menu and Guide components by the render function

Correctly create global variables in React

As title. I've searched about this problem on this site but I didn't find a solution for my case.
I've defined a global variables in public/static/js/A.js in my Visual Studio project:
var pVariable=new Class1();
There is a function LoadList() in Class1.
That variable will be used in several functions in my project, so I set as a global variable, and I included the JS file to public/index.html in the same project:
<script type="text/javascript" src="%PUBLIC_URL%/static/js/A.js"></script>
I use that variable in src/Clsb.js in the same project....
var alist=pVariable.LoadList();
export default class Clsb extends Component{
render(){
return (<Table dataSource={alist} />);
}
}
When I start debug in Visual Studio , I got an error:Failed to compile: 'pVariable' is not defined no-undef
But I am sure the JS file contains that variable is included. Could someone guide me to fix where I made it wrong?
You can do that by storing the variable in window variable
first store the value of your variable in A.js like this
window.pie = 3.1416;
And you can see the variable value in your Clsb.js component like
console.log(window.pie);
As phuzi said in the comment to your question, declaring global variables in react is a bad idea, in this case the ideal would be to use redux, or else the context api (context hook) so you can access and make the variable available throughout your system.
Link to docs
https://reactjs.org/docs/context.html
👇 context with functional component
let's create a context like hook
/src/context.js
import React, { createContext, useState, useContext} from "react";
const UserContext = createContext();
export default function UserProvider({ children }) {
//your variables
//example
const [person, setPerson] = useState('John');
return (
<UserContext.Provider
value={{
person //variables to export
}}
>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
if (!context) throw new Error("useUser must be used within a CountProvider");
const { person } = context;
return { person };
}
after creating the context, around your app you need to place the provider
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import UserProvider from "./src/context.js";
ReactDOM.render(
<UserProvider>
<React.StrictMode>
<App />
</React.StrictMode>
</UserProvider>,
document.getElementById("root")
);
after you already have the provider you can access any file
src/page.js
import React from "react";
import { useUser } from "./context.js";
const Page = (props) => {
const { getPerson } = useUser(); //variable available by context
return (<h1>Test h1</h1>)
};
export default Page ;
obs: i didn't test the code
Global variables is not a good practice in React. Whenever you find you find yourself needing that, it's most likely that what you want us instead Global state Management.
My recommendation is :
-first to try React's built in global state Management toolsn like Context API https://reactjs.org/docs/context.html
-Then if the first doesn't serve your need, try third party state Management libraries like redux from https://react-redux.js.org/introduction/ or mobx

Named import in React

In this line:
import React, { Component } from "react";
why the braces are only around Component and not also on 'React'?
Here's a great answer that explains default and named imports in ES6
Let's say we have a class named Foo that I want to import. If I want to get the default export, I would do:
import Foo from './foo.js';
If I wanted a specific function inside the foo file, I would use the curly braces.
import { fooFunction } from './foo.js';
Note, this isn't a React feature, but ES6. Likely you are using babel to transpile your code from ES6 to ES5.
To create something similar in react. Lets take this following example.
someobject.js
const someobject = {
somefunc1: ()=>console.log("hello 1"),
somefunc2: ()=>console.log("hello 2")
}
export default someobject;
app.js
import someobject, { somefunc1, somefunc2 } from "./someobject";
someobject.somefunc1(); //hello 1
someobject.somefunc2(); //hello 2
somefunc1(); //hello 1
somefunc2(); //hello 2
export defaul
In the React module the default export is the React object and it also has a named export Component1, something like this:
// assuming React and Component are predefined
export default React
export Component
Coincidentally Component is also available on the React object, so it is not necessary to import separately, although some people prefer your approach. For example this is possible:
// MyComponent.js
import React from 'react'
class MyComponent extends React.Component {}
More information about ES6 module syntax can be found here.
1 Note that actually the React library does not have a named export Component as in the example above, however Component is a property on the default export and so due to the way that ES6 packages are transpiled by Babel, this becomes a named export, the behaviour then being as in the example above.
Import react will import the default react package, Component with braces then specifies a particular element of the React package. React by default will not need braces as it is the default import package.
import React, { Component } from "react";
Hope this helps
That is because the default export module in the react library is React, and there can be only one default export, even though you can export many other components, but only one can be default. Other components of the React library can then be destructured.
React is a module containing different methods, When using just React word, you import the whole module, so you can use React.Component (in this case dot notation reference to a method inside the module).
So if you need to import method? you will use braces, why?
because you import method between many methods in one module, So it's able to increase & decrease, so you can import {a, b, c, r, w, q} that's methods inside one class or one module, So you can see that if you using
import {Component} from 'react';
Now you can use Component word direct without dot reference like react.component.
So React module is exported by default, Here I need all the React module and I will use it with all methods, {Component} here exported by name, I need specific method from React library not all react library
and please check it too When should I use curly braces for ES6 import?
in the import import React, { Component } from "react"; we put the Component in braces because it is not the default export. however React is,... look at the following example
import React from "react";
export const Fun1 = () => {
return (
<React.Fragment>
<h1>this is fun 1</h1>
</React.Fragment>
);
};
export const Fun2 = () => {
return (
<React.Fragment>
<h1>this is fun 2</h1>
</React.Fragment>
);
};
const Fun3 = () => {
return (
<React.Fragment>
<h1>this is fun 3</h1>
</React.Fragment>
);
};
export default Fun3;
if we save the above file under example.js we can import the components in exmpample.js file as
import Fun3, {Fun1, Fun2} from "example";
therefore Fun3 is the default export and the other components Fun1 and Fun2 are not

parentheses around import ES6

I'm learning React Native, just curious about the parentheses in the first line of import
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
class HelloWorldApp extends Component {
render() {
return (
<Text>Hello world</Text>
);
}
}
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
Why wrap Component with {} but not React?
React is the default export (there can only be one of these per module). Default exports can be imported like this:
import React from "react";
Component is a named export (there can be many of these). Named exports are imported like this:
import { Component } from "react";
What you're seeing is both of these things imported on the same line.
default exports aren't automatically available everywhere, so they still need importing.
Note that the reason React needs importing at all is because of the way that JSX is transformed into JS - React needs to be available so <Text> can be transformed into React.createElement(Text, ....
I think it's just a matter of shorting the next invocations, since Component is a subclass of React, so that way you use React as default with all it has in it. and Component as a single class you'd use. By the way you use braces in import when you want something specific as a method or class, that is named export. There's a better explanation in here.
Having both named exports and a default export in a module
import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';
export default class MyNavbar extends React.Component {
render(){
return (
<Navbar className="navbar-dark" fluid>
...
</Navbar>
);
}
}

Categories

Resources