Creating a Simple React.js Application
Introduction
React is a JavaScript library for building user interfaces. This tutorial will walk you through setting up a new React project, creating components, and using state.
Prerequisites
- Basic knowledge of JavaScript.
- Node.js and npm installed. If not, download them.
Step 1: Setting up a New React Project
Create a new project using Create React App (CRA):
npx create-react-app react-tutorial
Navigate to your project
cd react-tutorial
Start your development server
npm start
After running the above command, your default browser should open with your React app running on http://localhost:3000/
.
Step 2: Creating a Simple Component
- Inside the
src
directory, create a new folder namedcomponents
. - Inside the
components
folder, create a file namedGreeting.js
. - Write your first functional component:
// Greeting.js
import React from 'react';
const Greeting = () => {
return <h1>Hello, React!</h1>;
}
export default Greeting;
4. Now, import and use this component in App.js
:
// App.js
import React from 'react';
import './App.css';
import Greeting from './components/Greeting';
function App() {
return (
<div className="App">
<Greeting />
</div>
);
}
export default App;
Step 3: Using State
State allows React components to change their output over time in response to user actions, network responses, etc.
- Update the
Greeting.js
component to include a button that changes the greeting message:
import React, { useState } from 'react';
const Greeting = () => {
const [message, setMessage] = useState('Hello, React!');
const changeMessage = () => {
setMessage('Goodbye, React!');
}
return (
<div>
<h1>{message}</h1>
<button onClick={changeMessage}>Change Message</button>
</div>
);
}
export default Greeting;
Here, useState
is a hook that lets you add React state to function components.
Step 4: Styling your Component
- Create a new file in the
components
folder namedGreeting.css
. - Add some basic styling:
/* Greeting.css */
button {
padding: 10px 15px;
background-color: #4CAF50;
border: none;
color: white;
cursor: pointer;
margin-top: 10px;
}
button:hover {
background-color: #45a049;
}
3. Import the CSS file in Greeting.js
:
import './Greeting.css';
You’ve now set up a basic React application, created a functional component, used state to update the component’s output, and applied some basic styling. This is just the tip of the iceberg in terms of React’s capabilities. From here, you can explore more advanced topics such as hooks, context, routing, and interacting with APIs. Happy coding!