Certainly! I'll provide a few basic examples to help you get started with React. These examples assume you have a basic understanding of JavaScript and HTML and are starting with React.
1. Setting Up Your React Environment
To write and run React code, you'll need a development environment. The easiest way to start is by using Create React App, which sets up everything for you.
npx create-react-app my-app
cd my-app
npm start
This will create a new project in the my-app directory and start a development server.
2. Basic React Component
A React component is a reusable piece of code that returns a React element. Let's start with a simple functional component:
// src/App.js
import React from 'react';
function Greeting() {
return <h1>Hello, welcome to React!</h1>;
}
export default Greeting;
This Greeting component is a function that returns a piece of JSX, a syntax extension that looks like HTML. To render this component, you'll import it and use it in your app.
3. Using Props
Props (short for properties) are how you pass data from one component to another. Let's enhance the previous example to use props.
// src/App.js
import React from 'react';
// A functional component that takes 'name' as a prop
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
export default App;
Here, the Greeting component takes in a name prop and displays a personalized greeting.
4. Using State with Hooks
React Hooks, like useState, allow you to add state to functional components. Here's an example of a counter:
// src/App.js
import React, { useState } from 'react';
function Counter() {
// Declare a new state variable, "count", and a function to update it "setCount"
const [count, setCount] = useState(0);
return (
<div>
<p>Current count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
In this example, the useState hook is used to create a state variable count and a function setCount to update it. The button increases the count when clicked, and the current count is displayed in a paragraph tag.
5. Handling Events
React uses synthetic events to handle user interactions, similar to standard DOM events but with cross-browser compatibility.
// src/App.js
import React from 'react';
function ButtonClick() {
const handleClick = (event) => {
alert("Button was clicked!");
console.log("Event details:", event);
};
return <button onClick={handleClick}>Click Me!</button>;
}
function App() {
return (
<div>
<ButtonClick />
</div>
);
}
export default App;
This example shows an alert when the button is clicked. The handleClick function is triggered by the onClick event.
6. Fetching Data (Example with useEffect)
To fetch data from an API, you can use the useEffect hook to handle side-effects like network requests.
// src/App.js
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, []); // Empty array means this effect runs once when the component mounts
if (loading) {
return <p>Loading...</p>;
}
return (
<ul>
{data.slice(0, 5).map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
function App() {
return (
<div>
<h1>Data from API:</h1>
<DataFetcher />
</div>
);
}
export default App;
This component fetches data from a public API and displays the titles of the first five posts. The useEffect hook is used to perform the fetch operation and update the state once the data is retrieved.
These examples should give you a solid foundation to start experimenting with React. As you become more comfortable, you can explore more advanced concepts like context, routing, and more comprehensive state management solutions. Happy coding!