React makes building interactive user interfaces straightforward.
Instead of manually updating the DOM when data changes, you describe what the UI should look like and React handles the updates.Let's build your first React application from scratch.
Setting Up Your First React Project
The fastest way to start a React project is with Vite:
npm create vite@latest my-react-app
cd my-react-app
npm install
npm run dev
This creates a new React project and starts the development server. Open your browser to see your app running.
Understanding the Project Structure
my-react-app/
├── public/
│ └── index.html // The HTML file that loads your React app
├── src/
│ ├── App.jsx // Your main component
│ ├── main.jsx // Entry point that renders your app
│ ├── index.css
│ └── App.css
├── package.json // Project dependencies and script
└── vite.config.js
Your First Component
Open src/App.jsx. This is a React component - a function that returns JSX:
function App() {
return (
<div className="App">
<h1>Hello React!</h1>
</div>
)
}
export default App
JSX: JavaScript + HTML
JSX lets you write HTML-like syntax in JavaScript, but with a few differences:
function App() {
const name = "Miguel";
return (
<div className="container"> {/* className, not class */}
<h1>Hello {name}!</h1> {/* JavaScript expressions in {} */}
<img src="logo.png" /> {/* Self-closing tags need / */}
</div>
);
}
Key differences from HTML:
- Use className instead of class
- Self-closing tags always needed: <hr /> instead of <hr>
- Javascript expressions go in {}
Adding Custom Styles
App.jsx
function App() {
return (
<div className="welcome-card">
<h1 className="welcome-card--title">Welcome to React</h1>
<button className="welcome-card--button">Click me</button>
</div>
);
}
App.css
/* App.css */
.welcome-card {
text-align: center;
padding: 2rem;
& .welcome-card--title {
color: #333;
font-size: 2.5rem;
margin-bottom: 1rem;
}
& .welcome-card--button {
background-color: #007bff;
color: white;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
}
}
Inline Styles
function App() {
return (
<div style={{ textAlign: 'center', padding: '2rem' }}>
<h1 style={{ color: '#333', fontSize: '2.5rem' }}>Welcome to React</h1>
</div>
);
}
Components & Props
Props let you pass data to components, making them reusable:
// src/components/Greeting.jsx
function Greeting({ name, age }) {
return (
<div>
<h2>Hello, {name}!</h2>
<p>You are {age} years old.</p>
</div>
);
}
export default Greeting;
Then in your App.jsx you can re-use this component:
import Greeting from './components/Greeting';
function App() {
return (
<div className="App">
<Greeting name="Miguel" age={25} />
<Greeting name="Ana" age={30} />
</div>
);
}
export default App;
This is the foundation to build React applications. You can create components, style them and pass data with props.