You can simply return this in the User component:

return (
 <UsersList users={USERS} />
)

Then the UsersList component will become:

const UsersList = ( { users } : UsersListProps) => {
 if(!users?.length){
   return(
     <div>
       <h1>No users found</h1>
     </div>
   );
 }
 return(
  <ul>
   {users.map(({ id, name, image, places, placeCount }) => (
     <UserIListtem
      key={id} 
      name={name} 
      id={id} 
      image={image} 
      places={places} 
      placeCount={placeCount}/> 
   ))}
  </ul>
 );
}

And the UserIListtem component:

const UserIListtem = ({ name: user, id, image, placeCount, places: placeName }: User) => {
 return (
  <li>
   <div>
    <div>
     <img src={image} alt={placeName}/>
    </div>
    <div>{id}
     <h2>{user}</h2>
     <h3>{placeCount}</h3>
     </div>
   </div>
  </li>
 )
}

Remember to also change the UsersListProps interface to:

export interface UsersListProps {
 users: User[];
}

export interface User {
 id: number;
 name: string;
 image: string;
 placeCount: number;
 places: string;
}
Answer from Hakim Abdelcadir on Stack Overflow
🌐
Reddit
reddit.com › r/reactjs › how to pass an array as a prop in typescript react hooks
r/reactjs on Reddit: How to pass an array as a prop in typescript react hooks
November 29, 2021 -

I have difficulty passing an array as a prop to a component from the parent in react typescript.

The error I am getting is

Type '{ report:ReportData[]; }' is not assignable to type 'IntrinsicAttributes & ReportData & { children?: ReactNode; }'.
Property 'report' does not exist on type 'IntrinsicAttributes & ReportData & { children?: ReactNode; }'. Did you mean 'Port'?

import ReportComponent from '../Components/Reports/ReportComponent';
import { ReportData } from "../Types/ReportData.types";
const Report = () => {
 const [Report, setReport] = useState<ReportData[]>([]);
 ReportService.GetReport()
      .then((response) => {
        console.log(response.data.data);
        setReport(response.data.data);
        toast.success(response.data.message);
      }).catch((e) => {
        console.log(e);
      });

  return <ReportComponent report={Report}/>;

//ReportComponent

const ReportComponent: React.FC<ReportData> = (props:ReportData) => {
console.log("props",props)
return  <div className="row">
          
        </div>
}

I will appreciate help on fixing this

Thanks

Discussions

React - Pass an Array as Props
Tell us what’s happening: So I know that the challenge is asking to use the join method but i wanted to experiment a bit and see what would happen if I wouldn’t use it and it ends up rendering the array as “workoutcode… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
April 26, 2023
Reactjs/Typescript cannot pass array of items as property to child
Either Typescript or React, I assume Typescript, is apparently sticking the array into an object instead of passing the array as I expect it to. Can anyone figure out what I might be doing wrong here? ... Sign up to request clarification or add additional context in comments. ... To expand, this is a result of React components only taking objects as arguments (the props ... More on stackoverflow.com
🌐 stackoverflow.com
December 14, 2017
React - Pass an Array as Props
Tell us what’s happening: Describe your issue in detail here. I do not understand why my code is not running. It says it is unable to use the array function join(). Please help. Your code so far const List = (props) … More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
July 8, 2023
Passing arrays from one component to another, using props.
I had not attempted rendering this ... it as a prop. I was trying to console.log() the data before I tried rendering, to prove that it was there. I've passed plenty information to components throughout this sandbox app. But now, I'm experiencing issues when I try it outside of the lesson. Specifically, in this current attempt. Thank you for your effort. I guess I'll just keep searching : ) In theory though, is my understanding of React correct? Shouldn't I be able to pass an array as props and ... More on teamtreehouse.com
🌐 teamtreehouse.com
6
January 14, 2022
🌐
YouTube
youtube.com › watch
React TypeScript – How to Pass Objects & Arrays as Props Like a Pro - YouTube
How we can pass objects as props in the react-typescript application. We are also going to see how to pass an array of objects as props and how to define its...
Published   March 26, 2023
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
React - Pass an Array as Props - JavaScript
April 26, 2023 - { { /* Change code below this line */ } return {props.tasks.} { /* Change code above this line */ } }; class ToDo extends React...
🌐
Medium
careerwithvasanth.medium.com › react-problems-with-passing-array-as-a-prop-a124fa02d511
React — Problems with passing array as a prop | by Vasanth Bhat | Medium
November 26, 2021 - But when you pass reference types as props, you start facing few unwanted scenario’s. Let’s consider below example; Home.js is having two props Child1 and Child2 and both take user array as a prop. Child1 modifies the array and renders the items, where as child2 just renders the items. ... import React from 'react'import {View} from 'react-native'import Child1 from './Child1';import Child2 from './Child2';export default function Home() {const user = [{name: 'User 1'},{name: 'User 2'},{name: 'User 3'}]return (<View><Child1 userDetails={user}/><Child2 userDetails={user}/></View>)}
🌐
Bobby Hadz
bobbyhadz.com › blog › react-pass-array-as-prop
Pass an Array as a prop to a component in React.js | bobbyhadz
... Copied!function Books({arr}) ... } When passing any prop other than a string to a React component, we have to wrap the value in curly braces....
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
React - Pass an Array as Props - The freeCodeCamp Forum
July 8, 2023 - { { /* Change code below this line */ } return { props.tasks.join(",") } ; { /* Change code above this line */ } }; class ToDo extends React.Component { constructor(props) { super(props); } render() { return ( To Do List...
🌐
Webdevtutor
webdevtutor.net › blog › typescript-react-props-array
A Comprehensive Guide to Using Arrays in React Props with TypeScript
By passing the array [1, 2, 3] to the items prop of MyComponent, TypeScript will validate that the prop receives an array of numbers as intended. In some cases, you may need to work with dynamic arrays in your React components. To handle dynamic array props, you can use TypeScript's generics ...
🌐
Team Treehouse
teamtreehouse.com › community › passing-arrays-from-one-component-to-another-using-props
Passing arrays from one component to another, using props. (Example) | Treehouse Community
January 14, 2022 - "But maybe that's too many calls to the server." My understanding of React was since I've already got the necessary data (emails) from a route used in the MenuItems component, that I'd be able to map through that data, put it in an array and pass it as props to the StatLine component.
🌐
Reddit
reddit.com › r/reactjs › can't pass array as props to child functions [beginner]
r/reactjs on Reddit: Can't pass array as props to child functions [beginner]
March 24, 2021 -

Hello!

I'm taking my first steps into React -and JV- and encounter a problem I can't solve. It looks like one of those that are actually incredibly simple, the answer just in front of my eyes. But, dammit, I can't see it.

With create-react-app I've been messing with the App.js file. I'm trying to define an Array of objects, and then pass those objects to child functions.

App function:

import React from 'react'

const App = () => {
  const parts = [
    {
      name: 'This is part 1',
      exercises: 20
    },
    {
      name: 'Part two it is',
      exercises: 5
    },
    {
      name: 'Threeee',
      exercises: 16
    }
  ]
  console.log(parts)     //output array: (3) [{…}, {…}, {…}]
  console.log(parts[0])      //output object:{name: "This is part 1", exercises: 20}  
  return (
    <div>
      <Content parts={parts} />
    </div>
  )
}

Content function:

const Content = (props) => {
  console.log(props)  //output object!?: {parts: Array(3)}
  console.log(props[0])  //output: undefined
  return (
    <>
    <Part1 props={props[0]} />
    <Part2 props={props[1]} />
    <Part3 props={props[2]} />
    </>
  )
}

part1 function (part2 and part3 are the same as this):

const Part1 = (props2) => {
  console.log(props2)  //output object!?: {props: undefined}
  return (
    <>
    <p>
      {props2.name} {props2.exercises}
    </p>
    </>
  )
}

What I need to accomplish for the exercise is to only pass the array parts in App function like this: <Content parts={parts} />

Then Content function should use the object indexed 0 on the array and pass it to Part1, which should return the <p> code.

I guess there's an error when passing the array to Content. It gets converted to an object and then I cant use the index method. If I try props[0] I get nothing for it is undefined. If I try to console.log(props[0].name) I get the error: TypeError: Cannot read property 'name' of undefined

How can I pass the array to the child functions? I know the structure of the app might not be ideal, but it's exercise 1.4 for the Fullstackopen Course, by the University of Helsinki. I changed the actual content and eliminated some code to avoid trouble.

I will appreciate any help with the code and with the way I presented my problem, I also have to learn how to do that! Thanks!

Top answer
1 of 2
75

The curly braces only need to be used within JSX elements. Like this:

<MyComponent somProp={['something']} />

In the case above, the {} is the way of saying: "Evaluate the expression that I passed within and pass it as a prop". Within the {} you can pass any valid JavaScript object or expression. Note that if you pass a string, and specifically for strings, you don't need the curly braces... like <MyComponent somProp="something" />.

The above code is the equivalent of this:

var myArray = ['something'];
<MyComponent somProp={myArray} />
2 of 2
7

You actually don't need to specify PropTypes at all to use props. It's just a good way to document and verify prop types during development.

You are using the {} correctly. {} will return the value of the expression inside.

However, {['everyone']} doesn't make much sense. Here you are asking React to return the value of the array itself, rather than one of the elements/values within the array.

To get the first value out of your array, you should be doing: {this.props.config[0]} since the value "everyone" is at the 0 index of the array.

If your array had multiple values, you would do something along the lines of:

render: function() {
  var values = this.props.config.map(function(value, i){
    return (
      <p>value</p>
    );
  });

  return (
    <div className="navigation">
      helloworld {values};
    </div>
  );
}

If you truly to mean to actually print out the array itself, and not a particular value within it, you have two good options:

render: function() {
  return (
    <div className="navigation">
      helloworld {this.props.config.toString()};
    </div>
  );
}

Or

render: function() {
  return (
    <div className="navigation">
      helloworld {JSON.stringify(this.props.config)};
    </div>
  );
}
🌐
Xerosource
xerosource.com › pass-array-of-objects-as-props-react-typescript
Pass Array of Objects as Props React TypeScript?
June 24, 2023 - BEST IT SOLUTION Optimal Business Solutions for the Next Milestone. We empower businesses by providing innovative IT solutions, enabling them to adapt effectively and enhance their competitive edge. Let’s Get Started View Our Services ABOUT US Enabling businesses to thrive and achieve excellence.
🌐
CopyProgramming
copyprogramming.com › howto › typescript-array-of-objects-as-props
Reactjs: Using an array of objects in Typescript as component props
May 25, 2023 - Solution 1: To accomplish this, you can simply return the following code in the component: The component will then appear as follows: Also, modify the interface to: Solution 2: Alternatively, you can replace props with users: Array and send the entire array to load the data into your UserIListtem.
🌐
HatchJS
hatchjs.com › home › react typescript: how to pass an array of objects as a prop
React TypeScript: How to Pass an Array of Objects as a Prop
January 5, 2024 - Learn how to pass an array of objects as a prop in React TypeScript with this step-by-step guide. This is a common task that can be easily accomplished with the use of the spread operator. We'll also cover some best practices for passing arrays ...
🌐
GitHub
github.com › Manish-Giri › FreeCodeCamp › blob › master › curriculum › challenges › english › 03-front-end-libraries › react › pass-an-array-as-props.english.md
FreeCodeCamp/curriculum/challenges/english/03-front-end-libraries/react/pass-an-array-as-props.english.md at master · Manish-Giri/FreeCodeCamp
When rendering each List from the ToDo component, pass in a tasks property assigned to an array of to-do tasks, for example ["walk dog", "workout"]. Then access this tasks array in the List component, showing its value within the p element.
Author   Manish-Giri
🌐
CodeSandbox
codesandbox.io › s › 15-pass-an-array-as-props-o86f8
15. Pass an Array as Props - CodeSandbox
August 20, 2019 - To pass an array to a JSX element, it must be treated as JavaScript and wrapped in curly braces.\n\n \n \n {props.colors.join(', ')} \n\nThis will join all colors array items into a comma separated string and produce:\n\n green, blue, red
Published   Aug 19, 2019
Author   sasigit7