Miloš Đorić
Miloš Đorić

Reputation: 47

Passing data to lodash map() function - functional components

This is example of my products.json

{
  "products": [
    {
      "product_id": 1,
      "product_name": "M-Z-8Nm",
      "supplier_id": 1,
      "product_cat": "Motori",
      "product_subcat": "Zglobni motori",
      "product_char": "8Nm",
      "product_uom": "kom",
      "product_quantity": "20",
      "product_commentar": ""
    },
    {
      "product_id": 2,
      "product_name": "M-P-10Nm",
      "supplier_id": 1,
      "product_cat": "Motori",
      "product_subcat": "Pomoćni motori",
      "product_char": "10Nm",
      "product_uom": "kom",
      "product_quantity": "13",
      "product_commentar": ""
    }
  ]
}

Now, in component under i am mapping options for Select field from products.json ( react-select ) and return it. In this example i am mapping product-name as option for select button.

I would like to make this component reusable so i could pass data with props and use it (ie. product-id instead of product-name. Data from props are stored in const extractProps which is typeof String (but dont need to be).

I have problem replacing key from products product_name with data from props extractProps.

ReactSelectComponent.js:

import React from "react";
import Select from "react-select";
import FetchDataCustomHook from "./FetchDataCustomHook.js";
import _ from "lodash";

const ReactSelectComponent = (props) => {
    //  extractProps is typeof string and need to replace "product_name"
    const extractProps = props.propsFromForm
    const options = _.map(
        FetchDataCustomHook(),
        function (products) {
            return {label: products.product_name, value: products.product_name}
        });
    return (<Select options={options}/>)
}
export default ReactSelectComponent;

Upvotes: 1

Views: 132

Answers (1)

sebaslh12
sebaslh12

Reputation: 78

You don't really need lodash to accomplish that map, this is a solution using pure js:

const ReactSelectComponent = ({property}) => {
    const options = products.map((product) => {
        return { value: product[property], label: product[property] }
    });
    return (<Select options={options}/>);
}

If you want to use lodash then it the options would be like this:

const options = _.map(products, (product) => {
    return { value: product[property], label: product[property] }
})

And this is how you called the component <ReactSelectComponent property='product_name' />.

I stored the json you posted as the products variable.

Upvotes: 1

Related Questions