Do I need to import React for stateless functional components?

Around me (for example, blog posts, code) I see code for Actact functional components without changes in which React imported, even if it has never been used.

 import React, { PropTypes } from 'react'; function MyComponent({ foo, bar }) { ... return ...; } MyComponent.propTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.func.isRequired } export default MyComponent; 

I would say that there is no need to import React into functional components, and I thought it was just a remnant when the components were classes and were no longer needed.

I am also surprised that my linter does not complain about unused imports (it usually complains when I import something that is not in use).

Is there any reason to import React into functional components that I don't know about?

+5
source share
3 answers

Yes there is. Babel is switching JSX to using React :

 <div></div> 

To:

 React.createElement("div", null); 

So, your JSX is internally passed to use React.createElement in pure JavaScript that uses React . Remember that JSX is just syntactic sugar on top of pure JavaScript. Unless you import it specifically, it will report that React is undefined.

+15
source

What is the Responsive Responsive feature?

When you write a component with state, it has these three main parts (except for the whole logic):

1. constructor

2. life cycle methods

3. make

And try converting this part of the rendering to:

 React.createElement(element, null); //element will be the wrapper of all the jsx 

Now, when you write a stateless functional component, basically it only has a render constructor without a constructor, without a lifecycle method . Regardless of the fact that you return from this component is also converted to:

 React.createElement(element, null); 

So what is React importing for? Always keep in mind that we are writing JSX not the html that will be passed to babel .

Check the DOC for a non-JSX response .

Check out the converted version of the functional component from Babel.

Hope this helps you.

+4
source

You can import React into your recording file (index.js) and define the response of the global window.React = React in the index.js file. That way, you don’t have to import a response in each stateless component

0
source

Source: https://habr.com/ru/post/1268139/


All Articles