How do you create a React functional component?
React functional components are JavaScript functions that return React elements (JSX). They are the modern standard for writing React components, offering simplicity and leveraging React Hooks for managing state and side effects.
Basic Structure
A functional component is essentially a JavaScript function that takes 'props' (short for properties) as an argument and returns JSX. The name of the component should start with an uppercase letter.
import React from 'react';
function MyComponent() {
return (
<div>
<h1>Hello from MyComponent!</h1>
<p>This is a simple functional component.</p>
</div>
);
}
export default MyComponent;
Using Arrow Functions (Common Practice)
It's very common to define functional components using arrow function syntax for brevity and modern JavaScript consistency.
import React from 'react';
const MyArrowComponent = () => {
return (
<div>
<h2>Hello from MyArrowComponent!</h2>
</div>
);
};
export default MyArrowComponent;
Accepting Props
Components can receive data from their parent components via 'props'. Props are passed as the first argument to the functional component.
import React from 'react';
const Greeting = (props) => {
return (
<div>
<h3>Hello, {props.name}!</h3>
<p>{props.message}</p>
</div>
);
};
export default Greeting;
// Usage in a parent component:
// <Greeting name="Alice" message="Welcome to React!" />
Using Destructuring for Props
Destructuring props directly in the function signature is a clean and common way to access them.
import React from 'react';
const GreetingDestructured = ({ name, message }) => {
return (
<div>
<h3>Hello, {name}!</h3>
<p>{message}</p>
</div>
);
};
export default GreetingDestructured;
// Usage in a parent component:
// <GreetingDestructured name="Bob" message="Enjoy coding!" />
Using State with the useState Hook
Functional components manage their own state using React Hooks, such as the useState hook. This hook returns an array containing the current state value and a function to update it.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return (
<div>
<h4>Count: {count}</h4>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;