Recently I started learning react with ES5 but now trying to use Type script in my app. Can anyone please tell me why I am not able to print values using {this.props.people} but it is working as expected when i am using {this.state.people}. I have taken example from this site. Please suggest me what is missing here?
Site
import * as React from 'react';
class About extends React.Component<any, any> {
constructor(props: any) {
super(props);
console.log(About);
const people = [];
for (let i = 0; i < 10; i++) {
people.push({
name: i,
country: i + i
});
}
this.state = {people};
}
public render() {
return (
<div>
{this.props.people.map((person: any, index: number) => (
<p key={index}>Hello, {person.name} from {person.country}!</p>
))}
</div>
);
}
}
export default About;
Recently I started learning react with ES5 but now trying to use Type script in my app. Can anyone please tell me why I am not able to print values using {this.props.people} but it is working as expected when i am using {this.state.people}. I have taken example from this site. Please suggest me what is missing here?
Site
import * as React from 'react';
class About extends React.Component<any, any> {
constructor(props: any) {
super(props);
console.log(About);
const people = [];
for (let i = 0; i < 10; i++) {
people.push({
name: i,
country: i + i
});
}
this.state = {people};
}
public render() {
return (
<div>
{this.props.people.map((person: any, index: number) => (
<p key={index}>Hello, {person.name} from {person.country}!</p>
))}
</div>
);
}
}
export default About;
Share
Improve this question
edited Dec 2, 2017 at 22:55
str
45.1k18 gold badges114 silver badges134 bronze badges
asked Dec 2, 2017 at 22:40
DirtyMindDirtyMind
2,5912 gold badges28 silver badges46 bronze badges
2 Answers
Reset to default 7Because this.props.people
is something that is populated when your parent ponent send people prop. this.state.people
is accessible because you are setting it in your constructor.
And it has got nothing to do with ES5
or ES6
. BTW you are using ES6
from the arrow functions.
class Parent extends React.Component {
render(
return (
<Child people=[1, 2, 3] />
)
)
}
class Child extends React.Component {
constructor(props) {
this.state = {
people: [5, 6, 7]
}
}
render() {
return (
<div>
{this.props.people} // Will render [1, 2, 3], ing from Parent
{this.state.people} // Will render [5, 6, 7], ing from Constructor
</div>
)
}
}
This is because in your example the props for people is never passed down, it's simply generated in the constructor and set to the state, you would have to use this.state.people.
If you want to use props, you would have to pass down people via a parent ponent. Have a look at the ponents-props documentation