Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't resolve `Objects are not valid as a React child` Error – reduce method as bad guy?

Rendering the below component returns

Objects are not valid as a React child

import moment from "moment";

const PayrollRuns = (props) => {

    const runItems = props.payrollRuns.map((run) =>
        <div key={run.id} className="flex justify-between p-2 text-lg">
            <div>
                {moment(run.month.period).format('YYYY MMMM')}:
                Paid {run.payroll_run_items.length} talents
            </div>

            <div>
                {run.payroll_run_items.reduce((acc, value) => {
                  return value.amount;
                })}
            </div>
        </div>
    );

    return (
        <div className="runs-wrapper bg-white rounded-xl h-full w-48 shadow-sx-shadow p-4 flex flex-col">
            <h1 className="border-b-2 pb-4">Payroll Runs</h1>
            <div className="grow overflow-auto p-4">{runItems}</div>
        </div>
    )
}

export default PayrollRuns

I could drill down the issue to this part:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div>
    {run.payroll_run_items.reduce((acc, value) => {
      return value.amount;
    })}
</div>

So does the error mean that the reduce method returns an object rather than a single value? If yes, how to fix this? And if not, what else might be the issue?

>Solution :

Looks like you’re trying to get a single value by adding it from the payroll_run_items array.

You haven’t specified a start value for the accumulator, nor are you collecting the value.amount anywhere.

Here’s a simple example to achieve what you want:

const payroll_run_items = [{
  amount: 34,
  // Other properties
}, {
  amount: 35,
  // Other properties
}]

console.log(payroll_run_items.reduce((acc, value) => {
  return value.amount + acc; // Add 'value.amount' to 'acc'
}, 0)) // Specify a start value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading