Creating a Menu using React.js
Tags: react, javascript, tutorial, npm
Published: 2023-01-08 09:24:07

Menus are an essential tool for helping customers decide what to order and are a necessary part of the dining experience. It is typically displayed on paper or digitally, and it includes the names and prices of each dish along with a brief description of what the meal consists of, for example, the restaurant menu.

Menus vary in terms of the types of dishes that are offered. Some menus might focus on a particular type of cuisine, such as Italian, Chinese, or Nigerian, while others might offer a more diverse selection of dishes from different cuisines.

This tutorial will provide an overview of how to create a menu list using React.js.

Necessary steps for setting up the project or local environment.

Learn how to iterate over an array of menu items and render them as a list using the ul li elements tags.

For this project, TailwindCss was used for styling.

By the end of this tutorial, you will understand how to create a menu using React.js and be able to develop this project.

Prerequisite

1. Install node.js on your system.
2. Have an understanding of Javascript.
3. Understanding of how React.js works.

## Setting up the project or local environment

Create a folder in your desired location.

```
mkdir react-menulist
```
This will create a new folder called `react-menulist `in your specified path.

Next, cd into the project

```
cd react-menulist
```
This will change the previous directory to the current directory, where the `react-menulist` folder is located.

Inside the directory of our project

Create a react boilerplate using the **create-react-app** or **vite tools**; I prefer[ vite](https://vitejs.dev/).

```
npx create-react-app ./ or npx create-vite@latest ./
```
_**I am using ./ because I have created the folder and cd right into the directory**_

_**./ creates the react boilerplate for you right inside the created folder**_

In your terminal, install Tailwind CSS for styling your project and necessary dependencies.

To install [TailwindCSS](https://tailwindcss.com/), go to their documentation and follow the guidelines of your chosen framework.

![Tailwindcss](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iof6oo0l63d9k9aon6iw.png)

For this project, the following dependencies were installed:
```
npm install react-loader-spinner --save and npm install react-router-dom@6
```
![dependencies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s0gcfi4x95xog4dq62wy.png)
Start the application with these commands
```
npm run start or npm run dev
```

Using **npm run start (CRA)** or **npm run dev (VITE)** depends on how you create the React application.

Now we have our local environment working let's create the project

## Setting up the project

1. First, we'll create a separate file for our data. This will let us organize our code and keep related information together. It is also a useful way of refactoring the codebase.

To do this, simply create a new file in the root directory of your project and give it a descriptive name, such as `data.js`

Next, define your data in the file as an array or object.

**Example**: `data.js file` and it's content

![data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oobtc61fde5n3ah7u8cc.png)
_Import this data into other parts of your project as needed, and use it to display your item_.
2. Under the **src**, create a folder called` component`( this is optional and for organizational purposes), then create all the files you want to work with.

![components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqbimxp5rogwsd2qa5kr.png)
Next, create a `Header.jsx `and an `Home.jsx` inside the `component folder.
`
The purpose of `this Header.jsx` file is to create a **navigation menu.**
`Header.jsx`

```
import { useState } from 'react'
import { NavLink } from 'react-router-dom';
const data = [
    {
        title: 'All',
        link: '/',
    },
    {
        title: 'Breakfast',
        link: '/breakfast',
    },
    {
        title: 'Lunch',
        link: '/lunch',
    },
    {
        title: 'Dinner',
        link: '/dinner',
    },
    {
        title: 'Snacks',
        link: '/snacks',
    },
];

const Header = ({title}) => {
  const [navs]=useState(data)
  return (
        <>
            <div>
                <h1 className='h1'>{title}</h1>
            </div>
            <ul className='flex justify-center items-center gap-8'>
                {navs.map((nav, index) => (
                    <li key={index} className='li'>
                        <NavLink
                            to={nav.link}
                            className='navs'>
                            {nav.title}
                        </NavLink>
                    </li>
                ))}
            </ul>
        </>
    );
}

export default Header

```
In the `Header.jsx `file, we added an array of data and iterated through it using the** map() method**. Then we passed the iterated data to the **NavLink** component.

Using the **map() method**, we can quickly iterate through the menu list data and render it to the browser.

Next import the `Header.jsx` to the `Home.jsx` file.

**Home.jsx**

```
import React, { useState } from 'react'
import Header from './Header'
import { data } from '../../data'

const Home = () => {
    const [meals] = useState(data)
    return (
        <div>
            <Header title='Cr Menu💖' />
        </div>
    );
}

export default Home

```
_To view it in the browser, render the `Home.jsx `file into the root file, `App.jsx `which is created by default._

Remember, we installed **react-router-dom** as one of the dependencies, so that will be imported in `App.jsx` to help with the **navigation**.

**App.jsx**

```
import React from 'react'
import{Routes, Route}from 'react-router-dom'
import Home from './components/Home';


const App = () => {
    return (
        <Routes>
            <Route path='/' element={<Home />}></Route>
        </Routes>
    );
}

export default App

```
**Result**

![nav](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3xuu2us8xb26stswcjbj.png)

## To create a Menulist
3. Create a file called menulist.jsx

In this file, the meals stored in **useState()** are passed as a prop to the `Menulist.jsx `file, which will use the prop to iterate.

In the `Menlist.jsx` file, the prop will be received, and the **map() function** will be used to iterate through the data in `data.js` and retrieve each item.

```
import React from 'react'

const Menulist = ({meals}) => {
    return (
            <div className='meal-container'>
                {meals.map((meal) => (
                    <div key={meal.id}>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
                            <img src={meal.img} alt='img' className='img' />
                            <div className=" flex flex-col">
                                <div className='title-price'>
                                    <h5>{meal.title}</h5>
                                    <small>{meal.price}</small>
                                </div>
                                <div>
                                    <small className='ml-3 w-full'>--------------------------</small>
                                    <p className='para-menu'>{meal.para}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
        );
}

export default Menulist

```
To make it look beautiful and have a layout, use CSS or your desired CSS framework.

Next, import the `Menulist.jsx` into `Home.jsx` file

```
import React, { useState } from 'react'
import Header from './Header'
import { data } from '../../data'
import Menulist from './Menulist'

const Home = () => {
    const [meals] = useState(data)


    return (
        <div>
            <Header title='Cr Menu💖' />
            <Menulist meals={meals}
        </div>
    );
}

export default Home

```
**Result**

![list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1mferyy5cqwqaq6q26x.png)

## To get specific meals based on the category selected

4. To access a specific menu, such as `Breakfast.jsx`:

- import and render the `MenuList file`. In this specific file, use the **filter()** method on the prop passed to the `MenuList file` to select and display only the menu items that match a certain criterion from the database.

- The** filter() method **will return an array of items that pass the test.

![breakfastcomponent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3u4i87s32citc428ap0v.png)
**Result**

![breakfast](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hl5u1x5iyw4l7k0f1uij.png)

This process will be repeated for the other categories, such as lunch, dinner, and snacks, in their respective files.

## To make all components display on our browser

First of all, we will import **BrowserRouter **from the react-**router-dom library **to our `main.jsx or index.js`(this is the main entry point of the application). This component will wrap up the entire React application.

**Main.jsx**

```
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import { BrowserRouter } from 'react-router-dom'

ReactDOM.createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
)

```
Next, in `App.jsx` import **Routes**, and **Route** from **react-router-dom library**

**App.jsx**

```
import React from 'react'
import{Routes, Route}from 'react-router-dom'
import Breakfast from './components/Breakfast';
import Dinner from './components/Dinner';
import Home from './components/Home';
import Lunch from './components/Lunch';
import Snacks from './components/Snacks';

const App = () => {
    return (
        <Routes>
            <Route path='/' element={<Home />}></Route>
            <Route path='/breakfast' element={<Breakfast />}></Route>
            <Route path='/lunch' element={<Lunch />}></Route>
            <Route path='/dinner' element={<Dinner/>}></Route>
            <Route path='/snacks' element={<Snacks />}></Route> 
        </Routes>
    );
}

export default App

```

## Loading Aspect

5. This project includes the [react-loader-spinner](https://www.npmjs.com/package/react-loader-spinner) package as one of its dependencies:

**To use it**

- Ensure react-loader-spinner is installed

- Import it to where it will be used, for this project it was imported at the `Home.jsx`.

**A video demonstrating how it is used**

{% embed https://www.youtube.com/watch?v=pnpisvpSTUg&t=361s %}

In the `Home.jsx` file, set the **useState()** hook to **true**, and use a **setTimeout() **to change it to **false **after a certain amount of time. This will cause the loading spinner to disappear and the `MenuList `component to be displayed.

```
import React, { useState } from 'react'
import Header from './Header'
import { data } from '../../data'
import Menulist from './Menulist'
import { CirclesWithBar } from 'react-loader-spinner'

const Home = () => {
    const [meals] = useState(data)
    const [loading, setLoading] = useState(true)
    setTimeout(() => {
        if (loading) {
            setLoading(false);
        }
    }, 700);

    return (
        <div>
            <Header title='Cr Menu💖' />
            {loading && (
                <div className='flex items-center justify-center'>
                    <CirclesWithBar
                        height='50'
                        width='50'
                        color='#4fa94d'
                        wrapperStyle={{}}
                        wrapperClass=''
                        visible={true}
                        outerCircleColor=''
                        innerCircleColor=''
                        barColor=''
                        ariaLabel='circles-with-bar-loading'
                    />
                </div>
            )}
            {!loading && <Menulist meals={meals} />}
        </div>
    );
}

export default Home

```
**Result**

![Loadingspinner](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8qi152gysdt49cyoapw.png)

## Final Result

![Final](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3khnk7g23vyboqeib8oo.gif)

## Conclusion

In conclusion, a menu is an important aspect of running a business such as a restaurant, as it provides customers with information about the types of dishes and beverages that are available and helps them make informed decisions about what to order.

I hope you found this tutorial helpful and that you have learned something about using React.js to create a menu.

The source code is found in my [Repository](https://github.com/ijayhub/menulist)

[Live link](https://nigerian-meals.netlify.app/)

Thanks for reading💖