Overview
Components are the building blocks of React applications. They’re reusable pieces of code that return React elements describing what should appear on the screen.
Steps
- Set up a new React project (if you haven’t already):
npx create-react-app my-first-app
cd my-first-app
- Create a new file for your component:
# Create a components folder (optional but recommended)
mkdir -p src/components
# Create your component file
touch src/components/Greeting.js
- Define a functional component in
Greeting.js
:
import React from "react";
function Greeting(props) {
return (
<div className="greeting">
<h1>Hello, {props.name}!</h1>
<p>Welcome to React.</p>
</div>
);
}
export default Greeting;
- Use your component in
App.js
:
import React from "react";
import Greeting from "./components/Greeting";
import "./App.css";
function App() {
return (
<div className="App">
<Greeting name="World" />
<Greeting name="React Developer" />
</div>
);
}
export default App;
- Start your application:
npm start
Common Issues
- Forgetting to export the component: Always include
export default ComponentName
at the end of your component file - Importing from the wrong path: Double-check your import paths
- Case sensitivity: React component names must start with a capital letter
- Forgetting to close tags: All JSX elements must be properly closed (e.g.,
<img />
not<img>
)
Additional Notes
-
You can also define components as classes:
import React, { Component } from "react"; class Greeting extends Component { render() { return ( <div className="greeting"> <h1>Hello, {this.props.name}!</h1> <p>Welcome to React.</p> </div> ); } } export default Greeting;
-
Components can be nested inside other components
-
Props are read-only; if you need to modify data, use state instead
-
Keep components small and focused on a single responsibility
-
If using modern React, you can omit the React import:
import React from 'react';
(for React 17+)