use react js with json-server and Material-ui
- User
use react js with json-server and Material-ui
- Assistant
use react js with json-server and Material-ui
Creating a simple CRUD (Create, Read, Update, Delete) application with React.js, JSON-Server for a mock backend, and Material-UI for the user interface is a great way to learn about frontend and mock backend development. Below, you'll find a simplified guide on how to use these technologies together. This guide assumes you have a basic understanding of React and have Node.js installed on your machine.
Create a new React app:
npx create-react-app my-app
Move into your new app directory:
cd my-app
Install JSON Server:
npm install json-server
Install Material-UI:
npm install @mui/material @emotion/react @emotion/styled
Create a file named db.json in your project root:
{
"posts": [
{ "id": 1, "title": "Hello World", "author": "Jane Doe" }
]
}
Add a script to package.json to run JSON Server:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"json-server": "json-server --watch db.json --port 5000"
},
Start JSON Server:
npm run json-server
Create a new component inside the src directory. For example, PostList.js:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Container, List, ListItem, ListItemText, Divider } from '@mui/material';
const PostList = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetchPosts();
}, []);
const fetchPosts = async () => {
const response = await axios.get('http://localhost:5000/posts');
setPosts(response.data);
};
return (
<Container>
<List component="nav">
{posts.map(post => (
<React.Fragment key={post.id}>
<ListItem button>
<ListItemText primary={post.title} secondary={post.author} />
</ListItem>
<Divider />
</React.Fragment>
))}
</List>
</Container>
);
};
export default PostList;
Import and use your new component in App.js:
import React from 'react';
import PostList from './PostList';
function App() {
return (
<div className="App">
<PostList />
</div>
);
}
export default App;
You'll need to run your React app and JSON Server simultaneously. You can do this in two terminal tabs or windows:
In one terminal, start your React app:
npm start
In another terminal, start JSON Server:
npm run json-server
Open your browser and navigate to http://localhost:3000. You should see your application displaying data fetched from the JSON Server displayed using Material-UI components.
This guide provides a basic overview of setting up a project with React.js, JSON Server, and Material-UI. From here, you can expand the application by adding more features such as creating, updating, and deleting posts. Experiment with Material-UI's components to enhance the UI and improve user interaction.