Do I need to import React for stateless functional components?

痞子三分冷 提交于 2019-11-30 08:55:21

Yes, there is. Babel transpiles JSX to use React:

<div></div>

To:

React.createElement("div", null);

So your JSX is internally transpiled to use React.createElement in pure JavaScript, which does use React. Remember that JSX is just syntactic sugar over pure JavaScript. If you don't specifically import it, it will report that React isn't defined.

Mayank Shukla

What exactly a React Stateless Functional Component is?

When you write a stateful component it has basic these three parts (other than all the logic):

1. constructor

2. lifecycle methods

3. render

And react convert this render part into:

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

Now when you write a Stateless Functional Component it basically has only a render part no constructor, no lifecycle method. Whatever you return from this component will also get converted into:

React.createElement(element, null);

So that's why importing React is required. Always keep in mind that we write JSX not html, that will get transpiled by babel.

Check the DOC for React without JSX.

Check the converted version of a functional component by Babel.

Hope this will help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!