Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need to import React multiple times in parent and child components?

If you have a parent component file that already imports React, why does any of its rendered children files also need to import React? Is it just a safety measure in case those children are ever rendered somewhere else where React has not been imported yet?

like image 672
stackjlei Avatar asked Jun 07 '17 06:06

stackjlei


People also ask

Why do I need to import React in every component?

Explanations: The JSX gets internally into many React. createElement() function calls and each of them returns an object as shown above. Now because of this, we need to import React from “react” since internally every JSX is creating a React Component using JSX transformer.

Why is my child component rendering multiple times?

Cause: Inside your AddOrder component there is a useEffect that serves to prevent re-renders when the passed parameters were not changed, and among them it has a "new Date(). getTime()", I believe this is one of the main reasons why useEffect is always returning true, and requesting a re-render.

Why do we use import React?

Introduction. Importing and exporting in React JS will help us write modular code, i.e., splitting code into multiple files. Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing.

Can a child component have multiple parents?

A child component must have one parent at any one time. You can remove a child component from its parent and then add it to another parent if you wish.


2 Answers

In nodejs each file is a module, that has its own scope of variables. When you import variable into file (React for example) you add this variable to the module scope, but not to the global scope.

In case of webpack you can use providePlugin to easily make React variable global:

new webpack.ProvidePlugin({   React: 'react' // ReactJS module name in node_modules folder }) 

After that you are able to skip importing React variable in all of your modules. Webpack will do it itself where needed.

like image 98
GProst Avatar answered Oct 22 '22 07:10

GProst


If you use JSX and babel, you have to import React in every file because babel-preset-react will transpile your JSX code into React.createElement() calls, so this code

const Foo = () => <h1>Test</h1>; 

will be

var Foo = function Foo() {   return React.createElement(     "h1",     null,     "Test"   ); }; 

DEMO: Babel REPL

This is the reason why React should be accessible in the proper scope and one way to do it, is to import React in a file.

like image 26
Dawid Karabin Avatar answered Oct 22 '22 06:10

Dawid Karabin