A React component takes in props (input data) and returns a React element(s). In React, you can define a component in two ways:
- Functional components
- Class components
For instance, we can define an Input React component using the functional component syntax.
function Input(props) {
return <label>{props.label}<input type={props.type} /></label>
}
Alternatively, we can define the same Input component using the class syntax, which uses ES6 classes.
class Input extends React.Component {
render() {
return <label>{this.props.label}<input type={this.props.type} /></label>
}
}
Both are functionally equivalent, and can be used like this to create the RegistrationForm component:
const RegistrationForm = () => (
<form>
<Input label="Email" type="email" />
<Input label="Password" type="password" />
<button>Register</button>
</form>
);
Here, we are passing in the label and type props into the Input component, which we then used in the component's render method.
So which syntax should you use to define React components? Functional components are simpler to understand; after all, they are just JavaScript functions. Class components have a more complex syntax, but supports more features, such as holding a state, and can make use of different life-cycle methods, which we will cover soon. Therefore, if your component does not need these additional features, then you should prefer the functional syntax over the class syntax.