TypeError: Cannot read property 'props' of undefined - even that i pass some data in props to that component

Asked
Active3 hr before
Viewed126 times

9 Answers

propsundefinedcomponenttypeerrorpropertycannot
90%

You rewrite the context of the class method when you pass it to props like this because of JS OOP system. So to make it work there are several approaches:, 2 try replace onDelete and handleDelete methods with arrow function then you can use this on the merhods. – Metalik Jun 14 '18 at 16:47 ,TLDR: The specific problem in your cod is stated in the paragraph near the end of this answer.

1) This is not so good because bind always returns new function and your component will re-render even if there are no updates in props

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    render() {
        return (
            <div className="App">
                <StreetFighter />
            </div>
        );
    }
}

class StreetFighter extends Component {
    constructor(props) {
        super(props);
        this.state = {
            characters: [
                'Chun-Li',
                'Guile',
                'Ryu',
                'Ken',
                'E.Honda',
                'Dhalsim',
            ],
        };
    }
    render() {
        let characters = this.state.characters;
        characters = characters.map((char, index) => {
            return (
                <Character char={char} key={index} onDelete={this.onDelete.bind(this)} />
            );
        });
        return (
            <div>
                <p>Street Fighter Characters</p>
                <ul>{characters}</ul>
            </div>
        );
    }
    onDelete(chosenCharacter) {
        let updatedCharactersList = this.state.characters.filter(
            (char, index) => {
                return chosenCharacter !== char;
            }
        );

        this.setState({
            characters: updatedCharactersList,
        });
    }
}

class Character extends Component {
    render() {
        return (
            <li>
                <div className="character">
                    <span className="character-name">{this.props.char}</span>
                    <span
                        className="character-delete"
                        onClick={this.handleDelete.bind(this)}
                        > x </span>
                </div>
            </li>
        )
    };

    handleDelete() {
        this.props.onDelete(this.props.char);
    }
}


export default App;

2) In my code I use arrow functions as class properties for such cases (it's one of the most common solutions, I think)

class Character extends Component {
    render() {
        return (
            <li>
                <div className="character">
                    <span className="character-name">{this.props.char}</span>
                    <span
                        className="character-delete"
                        onClick={this.handleDelete}
                        > x </span>
                </div>
            </li>
        )
    };

    handleDelete = () => {
        this.props.onDelete(this.props.char);
    }
}
load more v
88%

According to the compiler, props does not exist. However, through the Player SFC, I am passing in the score property to the Counter component:,I opted to use class Counter extends React.Component instead of const Counter = React.createClass(). This fixed the problem with this not being defined.,I would maybe look into updating the syntax for the counter class. I would change it from a class to a function, for me this is just more explicit with the intentions of the component. it would look similar to the syntax of your player component and allows you to pass the props component explicitly.

const Counter = React.createClass({
  propTypes: {
    score: React.PropTypes.number.isRequired,
  },
  render: () => {
    return (
      <div className="counter">
        <button className="counter-action decrement"> - </button>
        <div className="counter-score"> {this.props.score} </div>
        <button className="counter-action increment"> + </button>
      </div>
    );
  }
});  
load more v
72%

Pretag
 Pretag team - issue, fix, solve, resolve
65%

At first, this component looks pretty straightforward. All this component does is receive a list of fish objects via props and render a Fish component for each one, passing down a couple of props to each fish. However, if you create this component and add to a real React app, it will fail. You will see an error that looks like:,If you are a React developer or are just learning to program in JavaScript, you might have run into this dreaded error while trying to read a property off of the this keyword:,So you've diagnosed the problem. You need to make sure that your functions have access to the this context of your class component! To do this, you can use ES6 arrow functions.

1TypeError: Cannot read property '<your property name>' of undefined
load more v
75%

 > Uncaught TypeError: Cannot read property 'props' of null , > Uncaught TypeError: Cannot read property 'color' of undefined ,It's pretty easy to see how to pass information from a parent component to a child component that it is calling. We've already looked at how to use  props  to do that.

 ChangeColorButton.js :

import React from 'react';

class ChangeColorButton extends React.Component {
  render() {
    return (
      <button >Change the color</button>
    );
  }
} 

export default ChangeColorButton;
load more v
40%

When defining a Class component, all of the passed in props are automatically assigned to the props instance variable, accessible as this.props. The this.props variable contains the object that would be passed as an argument to a function version of the component.,When using class components, events are handled in the same way as with function components (e.g., using the onClick prop). The main difference is that event handler callbacks are usually defined as separate methods of the class:,As mentioned in Introduction to React, it’s also possible to define React Components using ES 6 class syntax:

When defining a Class component, all of the passed in props are automatically assigned to the props instance variable, accessible as this.props. The this.props variable contains the object that would be passed as an argument to a function version of the component.

//Define a component representing information about a user
class UserInfo extends Component {
    render() {
        //access the individual props from inside the `this.props` object
        let userName = this.props.userName;
        let descriptor = this.props.descriptor;

        return (
            <div>
                <h1>{userName}</h1>
                <p>Hello, my name is {name} and I am a {descriptor}</p>
            </div>
        )        
    }
}

let userInfo = <UserInfo userName="Ethel" descriptor="Aardvark" />;
load more v
22%

TL;DR - If you are not in the mode for reading or you just want the bottom line, then here it is,TypeError: Cannot read property ‘map’ of undefined,We could also use an else statement if we want to render something else like a spinner or some text:

// Just a data fetching function
const fetchURL = "https://jsonplaceholder.typicode.com/todos/";
const getItems = () => fetch(fetchURL).then(res => res.json());

function App() {
  const [items, setItems] = useState();

  useEffect(() => {
    getItems().then(data => setItems(data));
  }, []);

  return (
    <div>
      {items.map(item => (
        <div key={item.id}>{item.title}</div>
      ))}
    </div>
  );
}
load more v
60%

Hi have the following link in DefaultHeader.js on which I cam calling logout function of DefaultLayout.js, but after click on that link if get error. TypeError: Cannot read property 'props' of undefined.,Hi @shashibeit Thanks for your question, which is more about JS ES6 classes and binding event handlers, and React way of handling events. It's not related to CoreUI itself., The text was updated successfully, but these errors were encountered:

 <DropdownMenu right style={{ right: "auto" }}>          
              <DropdownItem>
               <a onClick={this.props.logout()}><i className="fa fa-lock" /> Logout</a> 
              </DropdownItem>
</DropdownMenu>
load more v
48%

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.,React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.,Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.

function FancyButton(props) {
  return (
    <button className="FancyButton">
      {props.children}
    </button>
  );
}
load more v

Other "props-undefined" queries related to "TypeError: Cannot read property 'props' of undefined - even that i pass some data in props to that component"