Functional components are JavaScript functions that take props as arguments and return JSX elements. They are simpler and more concise. Here's an example:
import React from 'react'; const FunctionalComponent = (props) => { return <div>Hello, {props.name}!</div>; }; export default FunctionalComponent;
Class components are ES6 classes that extend from React.Component
. They have a render()
method that returns JSX. Class components are useful when you need to manage state or use lifecycle methods. Here's an example:
import React, { Component } from 'react'; class ClassComponent extends Component { render() { return <div>Hello, {this.props.name}!</div>; } } export default ClassComponent;
You can use these components in other parts of your application like this:
import React from 'react'; import ReactDOM from 'react-dom'; import FunctionalComponent from './FunctionalComponent'; import ClassComponent from './ClassComponent'; ReactDOM.render( <div> <FunctionalComponent name="John" /> <ClassComponent name="Jane" /> </div>, document.getElementById('root') );
In this example, we've imported the components and used them in the ReactDOM.render() function to render them to the DOM.