There's a little bit of a debate at work on whether it is necessary to import React
in stateless components and I can't find any docs about it. So:
//OPTION 1
import React, { PropTypes } from 'react';
//OPTION 2
import { PropTypes } from 'react';
export const Button = ({ action }) => {
return (
<button onClick={action}>Submit</button>
);
}
Button.propTypes = {
action: PropTypes.func.isRequired,
};
Some people say Option 1 is the best practice when using JSX; some other think component will fail with Option 2.
I have tried both and I can't see any difference, the component still works in both cases.
Option 1 or Option 2: which one is correct?
Based on that, we can go back to the original question of this article and understand the necessity to import React whenever we created a React component. Without it, the transformed JSX code would fail in the browser as React needs to be in scope to create components through its createElement function.
After Babel transformed your code which is written with JSX elements, into the React. createElement calls, you can see where React is used. If you forget to import React, it will be undefined and the createElement call will fail. So make sure to always import React in your functional components too!
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.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .
Use option 1 because babel will transform your jsx<button onClick={action}>Submit</button>
toReact.createElement("button", { onClick: action }, "Submit");
So as you see react must be in scope. You have two options:
It depends on how you're building your files. If you're using a module bundler like webpack and there's no notion of a global React module then leaving out React will throw the error React is not defined
.
This is because this:
let C = <div />
turns into:
let C = React.createElement("div", null)
So inside that particular module.. React
is not imported and therefore will trip on the undefined variable.
You can expose React
to the window namespace, then you don't need to import it into every file. That's up to you.
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