Reputation: 6968
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?
Upvotes: 11
Views: 934
Reputation: 20614
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.
Upvotes: 9
Reputation: 970
Use option 1 because babel will transform your jsx
<button onClick={action}>Submit</button>
to
React.createElement("button", { onClick: action }, "Submit");
So as you see react must be in scope. You have two options:
Upvotes: 13