PASSWORD RESET

Your destination for complete Tech news

How to check if an array includes a value in React JS?

3.93K 0
< 1 min read

You can use the method Array.prototype.includes() to check if an array includes a specific value in React JS, as you normally would in JavaScript. For example:

import React from 'react';

function App() {
  const fruits = ['apple', 'banana', 'orange', 'grape'];

  const checkIfIncludes = (value) => {
    return fruits.includes(value);
  };

  return (
    <div>
      <p>Does the array include 'banana'? {checkIfIncludes('banana') ? 'Yes' : 'No'}</p>
      <p>Does the array include 'watermelon'? {checkIfIncludes('watermelon') ? 'Yes' : 'No'}</p>
    </div>
  );
}

export default App;

In this example, the checkIfIncludes function uses the includes() method to determine whether the fruits array includes the provided value. The function returns true if the value is present in the array and false otherwise.

You can replace fruits with your own array and modify the values you’re checking for as needed.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.