How do I create a component in React?
Asked on Sep 22, 2024
Answer
In React, a component can be created as a function or a class. The most common approach is using a function component, which is simpler and leverages hooks for state and lifecycle management.
<!-- BEGIN COPY / PASTE -->
import React from 'react';
function MyComponent() {
return (
<div>
<h1>Hello, World!</h1>
<p>This is a simple React component.</p>
</div>
);
}
export default MyComponent;
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The component "MyComponent" is a function that returns JSX, which is a syntax extension for JavaScript that looks similar to HTML.
- The component is exported using "export default", allowing it to be imported and used in other parts of the application.
- Function components are preferred for their simplicity and ability to use React hooks for state management and side effects.
Recommended Links:
← Back to All Questions