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;
Because this.props.people
is something that is populated when your parent component 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], coming from Parent
{this.state.people} // Will render [5, 6, 7], coming 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 component. Have a look at the components-props documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With