Utilize a checkbox in ReactJS to sort data into categories of vegetarian and non-vegetarian options

I am currently developing a React project that utilizes an API to showcase restaurant menu data.

The structure of my data in the API is as follows:

[
  {
   "Name": "Chicken pizza",
   "Category": "Pizza",
   "Type": "non-veg",
   "Price": 376,
   "id": "1"
  },
  {
   "Name": "Paneer Cheese Pizza",
   "Category": "Pizza",
   "Type": "veg",
   "Price": 350,
   "id": "2"
  }
]

To display this data in my project, I am utilizing a map function like so:

{data.map(item =>
  <div>
   <div className='items' key={item.id}>
     <ul>
      <li className={item.Type === 'veg' ? 'veg' : 'non-veg'}></li>
      <li>{item.Name}</li>
      <li>₹ {item.Price}</li>
      <img src='/images/pizza1.jpg'/>
      <div className='hr'></div>
     </ul>
    </div>
   </div>
)}

Now, I want to incorporate a checkbox to show only the items with the "veg" type from my API. When unchecked, it should display all items. I have created a state for the checkbox like this:

const [veg, setVeg] = useState(false);

const vegOnly = () =>{
        setVeg(false);
    }

Here is the HTML code for the checkbox:

<label>
   <input type="checkbox" value={veg} onChange={vegOnly}/>
   Veg Only
</label>

I am looking for guidance on how to modify my code to filter between "veg" and "non-veg" types using the checkbox state without disrupting the existing functionality. Any ideas or suggestions are welcome!

You can find more details and clarification on my doubt via this sandbox link:

https://codesandbox.io/s/upbeat-bartik-8jpc2r?file=/src/App.js

I aim to utilize the checkbox to filter data based on "veg" and "non-veg" types effectively, but require assistance in writing the function for the checkbox state to achieve this feature.

Answer №1

To achieve this, you can filter the data accordingly. First, we check if the variable vegOnly is set to false; if it is, we simply return the original data. If vegOnly is true, we filter the data based on the value of the Type property.

const [data, setData] = useState([]); // initial value of []

const [vegOnly, setVegOnly] = useState(false);

const handleVegInputChange = (e) => {
  const isChecked = e.target.checked;
  setVegOnly(isChecked);
};

const filteredData =
  vegOnly === false ? data : data.filter((item) => item.Type === "veg");

Add the new input handler as shown below:

<label>
   <input type="checkbox" value={veg} onChange={handleVegInputChange}/>
   Veg Only
</label>

Make sure to iterate over the filteredData array instead of the original data:

return (
  <>
    {filteredData.map((item) => (
      <div>
        <div className="items" key={item.id}>
          <ul>
            <li className={item.Type === "veg" ? "veg" : "non-veg"}></li>
            <li>{item.Name}</li>
            <li>₹ {item.Price}</li>
            <img src="/images/pizza1.jpg" />
            <div className="hr"></div>
          </ul>
        </div>
      </div>
    ))}
  </>
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React: Material UI, Counting All the Rows

How many rows does Material UI in REACT support in its free and paid versions? I have a massive dataset exceeding 400 MB. Is this realistic or too ambitious? ...

Having trouble with Formik Chakra-ui select not recognizing the value property?

Having trouble submitting a form with a dropdown list. Formik doesn't seem to recognize the values from the options for some reason, and I'm not sure how to resolve this issue. const [value, setValue] = React.useState(""); const handleChange = (e ...

Refresh the react-table when an event occurs

I'm utilizing React and the react-table framework to display and list my data respectively. One issue I am facing is that after creating a new object in my database, I have trouble refreshing the table without navigating away from the view. My query ...

The React Typescript error message: "Type '' is not compatible with type 'null'"

I have started working on a simple todo app using React and TypeScript. As I am creating a context, I encountered an error regarding the value of the content provider. <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider> ...

Tips for resolving issues with adjusting row height when using expandable rows in a react virtualized list

I've recently encountered a challenge with expandable panels (Material-UI) within rows in a react virtualized list. The problem lies in the auto-adjusting heights of the panels, and despite researching similar issues on Stack Overflow and the react-vi ...

Using ReactJS and Hooks to update state after the .map() function

Trying to update the state using values from an array. Here is an example: const [state, setState] = useState({}); const test = [1, 2, 3]; test.map((item, i) => { setState({ ...state, [`item-${i}`]: item }); }); The current s ...

Updating the value of a different key within the same object using React Formik's setFieldValue方法

My objective is to automatically select a value in an option select when the onChange event occurs, and then use setFieldValue to set values for 2 Fields with key-value pairs within the same object. The issue I'm facing: Why does calling setFieldValu ...

Tips for using regular expressions with the find method in JavaScript?

Welcome to my Object: let data = [{ "title": "User info", "category": "personal", "userId": "abc12345" }, { "title": "Customer Info", "category": ...

The value of the state variable remains constant within the useEffect hook

Here's the code block where data is fetched and logged successfully using useEffect: const [allBooks, setAllBooks] = useState([]); useEffect(() => { axios.get('/all_books').then(res => { setAllBooks(res.data); console.log(re ...

Babel is failing to transpile the Modal component from material-ui-next to ES5

Issue with Babel transpiling Modal component from material-ui-next Here is my .babelrc configuration: { "presets": ["es2015", "react", "stage-1", "stage-2", "stage-3"] } This is the webpack-config.js setup: var webpack = require('webpack'); ...

Is there a way to insert a location icon into the react bootsrap FormControl text field component?

LocationSearchComponent.js I'm having an issue with empty icon showing as  const LocationSearchComponent = () => { return ( <Form className="locationForm"> <Form.Group> <Form.Contro ...

Error: Unable to convert null or undefined to an object | NextAuth

Recently, I've been attempting to implement a SignIn feature with Nextauth using the following code: import { getProviders, signIn as SignIntoProvider} from "next-auth/react"; function signIn({ providers }) { return ( <> ...

React class component experiencing issues with Material UI popover functionality

I'm new to using Material UI and find that all its documentation is based on function components, which I am not familiar with. I'm having trouble getting the popover to work - whenever I hover over the text, the function triggers but the popover ...

"Implementing a form submission feature in React.js that dynamically applies a class to the result element

I recently developed a basic BMI calculator using React.js. I am now attempting to implement a feature where if the calculated BMI result falls outside the range of a healthy BMI, the result text will be displayed in red color (I am utilizing styled-compon ...

What are some strategies to prevent prior asynchronous effects from interfering with a subsequent call to useEffect?

I have a straightforward component that initiates an asynchronous request when a certain state changes: const MyComponent = () => { const [currentState, setCurrentState] = useState(); const [currentResult, setCurrentResult] = useState(); useEffec ...

Generate dynamic routes in Next.js only when needed

I'm currently working on a project using NextJS to create a frontend for a database that contains thousands of products, with the expectation of significant growth. The site/products/ route is functioning well, but I wanted to add a route to view indi ...

The design of Next.js takes the spotlight away from the actual content on the

Recently, I've been working on implementing the Bottom Navigation feature from material-ui into my Next.js application. Unfortunately, I encountered an issue where the navigation bar was overshadowing the content at the bottom of the page. Despite my ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

Jest is throwing a TypeError, indicating that the provided function in the ClassName is not recognized as a valid function

I've encountered an issue with my JavaScript files. Here's a snippet of the code: import axios from "axios"; export default class SomeService { static getSomething(id) { return axios .get(API_BASE_URL + API_URL_Something ...

What is the best way to structure an array for JSON transmission between Express/NodeJS and ReactJS?

I have a query similar to the one posted on POST array of objects to REST API. However, I need a different formatting for my answer. My dataresults array contains Objects like: [ { reviewID: 5, TextComment: 'lol2314'}, { reviewID: 4, TextC ...