Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.props.xxx is undefined while using React with typescript but working properly in ES5?

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;
like image 201
DirtyMind Avatar asked Dec 02 '17 22:12

DirtyMind


2 Answers

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>
    )
  }
}
like image 200
Nandu Kalidindi Avatar answered Sep 29 '22 17:09

Nandu Kalidindi


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

like image 32
Stephen Avatar answered Sep 29 '22 18:09

Stephen