Stairss
Stairss

Reputation: 176

How to get value of the object with props in React

I've got a problem with getting the value of the object with props. I mean I've got data in JSON and I use fetch to get it, but that's actually a component and I want to have different data based on props. How to properly select the property in the object?

JSON:

{
  "example1": [
    {
      "title": "title1"
    }
  ],
  "example2": [
    {
      "title": "title2"
    }
  ]
}

Parent component:

import Child from './Child';
const Parent = () => {
    return ( 
        <div>
            <Child prop={'example1'}/>
        </div>
     );
}
 
export default Parent;

Child component:

import { useEffect, useState } from 'react';

const Child = ({prop}) => {
    const [data, setData] = useState({})
    const getData = async () => {
        await fetch('./data.json')
            .then(res => res.json())
            .then(data => {
                setData(data);

            })
    }
    useEffect(() => {
        getData()
    }, [])


    return ( 
        {`${data}.${prop}`?.map((item) => (
           <div>{item.title}</div>
        ))}
     );
}
 
export default Child;

If something is unclear feel free to ask :)

Upvotes: 0

Views: 2464

Answers (1)

sbcreates
sbcreates

Reputation: 209

Before you store your data in the data state you can extract the data you want using the prop prop passed into the component. Then you can set that to the data state.

.then(data => setData(data[prop]))

Upvotes: 2

Related Questions