Creating your own React component is straightforward. Here's a step-by-step guide:
1. Set Up a React Project (if you haven't already)
If you don't have a React project yet, you can create one using Vite (recommended) or Create React App (CRA).
Using Vite (Faster & Modern)
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev
Using Create React App (Legacy)
npx create-react-app my-react-app
cd my-react-app
npm start
2. Create a New Component
React components can be functional (recommended) or class-based.
Functional Component (Modern Approach)
Create a new file in the src folder, e.g., src/components/MyComponent.jsx:
import React from 'react';
// Functional Component
const MyComponent = () => {
return (
<div>
<h1>Hello, this is my custom component!</h1>
<p>Welcome to React!</p>
</div>
);
};
export default MyComponent;
Class Component (Legacy Approach)
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>
<h1>Hello from a Class Component!</h1>
</div>
);
}
}
export default MyComponent;
3. Use Your Component in Another File
Now, you can import and use your component in App.jsx (or any other component):
import MyComponent from './components/MyComponent';
function App() {
return (
<div>
<h1>Welcome to My App</h1>
<MyComponent /> {/* Using your custom component */}
</div>
);
}
export default App;
4. Add Props (Optional)
You can make your component dynamic by passing props:
In MyComponent.jsx:
const MyComponent = (props) => {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>Age: {props.age}</p>
</div>
);
};
export default MyComponent;
In App.jsx:
<MyComponent name="John" age={25} />
5. Add State (Optional)
If your component needs to manage its own state, use the useState hook (for functional components):
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default MyComponent;
6. Style Your Component (Optional)
You can style your component using CSS, inline styles, or CSS-in-JS libraries like styled-components.
Using CSS Modules (Recommended)
- Create
MyComponent.module.css:
.container {
background: lightblue;
padding: 20px;
}
- Apply it in
MyComponent.jsx:
import styles from './MyComponent.module.css';
const MyComponent = () => {
return (
<div className={styles.container}>
<h1>Styled Component</h1>
</div>
);
};
7. Run Your App
Start your development server:
npm run dev # For Vite
# or
npm start # For CRA
Your custom component should now appear in the browser!
Summary
- Create a new file (e.g.,
MyComponent.jsx).
- Define a function (or class) that returns JSX.
- Export the component (
export default MyComponent).
- Import and use it in another component.
- Add props, state, and styles as needed.
Would you like help with anything specific, like hooks, styling, or advanced features? 😊