Purva Parulekar
Purva Parulekar

Reputation: 45

Want to convert a component created with .map() to any another component so that .includes() can work on new component

I am running below code in React App.js .

FilteredData contains data as below

const filteredData = [{ fruitname: 'apple', fruitprice: '200'},
{ fruitname: 'mango', fruitprice: '500'}];

The main App.js contains below code

import React, {
useState,
} from 'react';

function Fruits({ filteredData }) {


const DisplayData = filteredData.map(
(info) => (
  <div>
    <ul id="result" type="disc">
      <li>{info.fruitname}</li>
    </ul>
  </div>

));



  const valuesnew =[...DisplayData.values()];
  const resultnew = valuesnew.includes('apple');

  return (
  <section>
  {String(resultnew)}
  </section>
  );
  }

App.propTypes = {
 filteredData: PropTypes.arrayOf(PropTypes.shape({
fruitname: PropTypes.string.isRequired,
fruitprice: PropTypes.string.isRequired,

 })),
};
export { App};
export default App;

The main agenda is that I need to check if 'apple' is present in filteredData (this data is coming from outside of app.js), to achieve that I am doing below

  1. putting filteredData in a const DisplayData
  2. converting DisplayData into an array valuesnew
  3. using .includes() method on valuesnew

But .includes() method gives false even though 'apple' is present . So .includes() is not working on the component.

Upvotes: 1

Views: 133

Answers (2)

RubenSmn
RubenSmn

Reputation: 4672

You can find things in a array with the find method. Its gives you the current element from the array where you can access its props such as fruitname.

If the array contains a object with the fruitname of apple then it will return that object else it will return undefined. In this case we check if its not undefined and thus true.

You can use it like so

const hasApple =
  filteredData.find((fruit) => fruit.fruitname === "apple") !== undefined;

Upvotes: 1

devpolo
devpolo

Reputation: 3349

Not sure to understand what you are trying to accomplish but this may help:

import { Children } from "react";

const ELEMENTS = [<p>apple</p>, <p>mango</p>, <p>banana</p>];

export default function App() {
  return Children.map(ELEMENTS, (child) => {
    if (child.props.children === "apple") {
      return child;
    }
    return null;
  });
}

EDIT: Why don't you simply did it on the return?

function Fruits({ filteredData }) {
  return (
    <section>
      {filteredData.map((info) => {

        if (info.fruitname !== "apple") return null;

        return (
          <div>
            <ul id="result" type="disc">
              <li>{info.fruitname}</li>
            </ul>
          </div>
        )
      })}
    </section>
  )
}

Upvotes: 0

Related Questions