1

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

1
  • 3
    Props is an Object, props.testData is an array. Commented Oct 29, 2019 at 16:00

2 Answers 2

2

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'
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.