JSON data with Rechart and React props

  javascript, reactjs, recharts

I am trying to use rechart to display the revenue data in my chart bar, It’s working if I put all together, but I want to use the chart in a new component, so I’m trying to use props but I can’t make it work like that.

Could someone help with this or suggest a better way.

thanks in advance

JSON

[
{"id": "AAPL",
    "company": "Apple",
    "revenue": [
      {"year":2016, "value":215.639},
      {"year":2017, "value":229.234},
      {"year":2018, "value":265.595},
      {"year":2019, "value":260.174},
      {"year":2020, "value":274.515}
    ]
},
{
    "id": "MSFT",
    "company": "Microsoft",
    "revenue": [
      {"year":2016, "value":215.639},
      {"year":2017, "value":229.234},
      {"year":2018, "value":265.595},
      {"year":2019, "value":260.174},
      {"year":2020, "value":274.515}
    ]
},
]

Main page

export default function CompanyDetails({companies}) {
    const {id} = useParams()

    return (
        <section id="companyDetails" className="container">
            {companies.filter(item => item.id === id).map(item => (
                <div key={item.id}>
                <CompanyMoneySource                
                    revenue={item.revenue.map(item => (
                        <> year={item.year} value={item.value} </>
                    ))}
                />
                </div>

            ))}
        </section>
    )
}

Chart component

import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts';

export default function CompanyMoneySource(props) {
    return (
        <article className="row row-cols-1 row-cols-lg-2">
            <div className="col order-lg-2">
                <h4>Produtos e serviços</h4>
            </div>

            <div className="col order-lg-1">
                <h4>Receita dos ultimos 5 anos</h4>
                <BarChart
                    width={500}
                    height={300}
                    data={props.revenue}
                    margin={{
                    top: 5,
                    right: 30,
                    left: 20,
                    bottom: 5,
                    }}
                    barSize={20}
                >
                    <XAxis dataKey={props.year} scale="point" padding={{ left: 10, right: 10 }} />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <CartesianGrid strokeDasharray="3 3" />
                    <Bar dataKey={props.value} fill="#8884d8" background={{ fill: '#eee' }} />
                </BarChart>
            </div>
        </article>
    )
}

Source: Ask Javascript Questions

LEAVE A COMMENT