How to create and compose React components
· Category: React
Short answer
React components are functions that accept props and return JSX. Composition is achieved by nesting components and passing elements via props or children.
Steps
- Define a component as a function.
- Accept
propsas an argument. - Return JSX describing the UI.
- Compose by nesting components inside one another or using the
childrenprop.
Example
function Button({ children, onClick }) {
return <button onClick={onClick}>{children}</button>;
}
function App() {
return (
<div>
<Button onClick={() => alert('Clicked!')}>Submit</Button>
</div>
);
}
Tips
- Keep components small and focused on a single responsibility.
- Use destructuring in the parameter list for cleaner prop access.
- Name components with PascalCase so React distinguishes them from HTML tags.