Ian Vink
Ian Vink

Reputation: 68770

ReactJS: When props is not an array?

Newbie question: I'm learning ReactJS+Typescript.

I have a simple interface describing an array of data:

interface IProfile {
  name: string;
  avatar_url: string;
  company: string;
}

const testData: IProfile[] = [
 { name: "Dan Abramov", avatar_url: "https://avatars0.githubusercontent.com/u/810438?v=4", company: "@facebook" },
 { name: "Sophie Alpert", avatar_url: "https://avatars2.githubusercontent.com/u/6820?v=4", company: "Humu" },
];

I have a simple call to an App function where I pass the array spread:

ReactDOM.render(
  <App {...testData} />,
  document.getElementById("root")
);

In the App the props is not an array though???:

class App extends React.Component<IProfile[]>  {

 constructor(props:IProfile[]) {
    super(props);
    console.log("props is array " + Array.isArray(props));  //false
 }

 public render() {
    return (<div> </div>);
 }

};

When I look at the props in the React Dev Tools in Chrome, it looks like an array though:

enter image description here

Upvotes: 1

Views: 53

Answers (2)

Dupocas
Dupocas

Reputation: 21317

props isn't an array is an object. Take a look at this piece of code from ReactElement.js from React's source

if (Object.freeze) {
    Object.freeze(element.props);
    Object.freeze(element);
} //just showing that props is in fact an object

You're spreading an array inside an object. If you pass it like

<App storeData={storeData} />

Inside app isArray evaluates to true now

Array.isArray(props.storeData) //true

Your current data structure looks like this

    const data = [
     { name: "Dan Abramov", avatar_url: "https://avatars0.githubusercontent.com/u/810438?v=4", company: "@facebook" },
     { name: "Sophie Alpert", avatar_url: "https://avatars2.githubusercontent.com/u/6820?v=4", company: "Humu" },
    ]

    const props = {...data}

    console.log(props)

Just an object with "number like" indexes (it's actually a string "0"). So when visualizing from react-dev-tools it looks like an array but they are actually properties of an object

{
   "0" : 'foo',
   "1" : 'bar'
}

Upvotes: 2

technicallynick
technicallynick

Reputation: 1592

It's not an array because you're spreading it. Spreading an array or an object removes it from the "container" and only puts in the values.

Upvotes: 0

Related Questions