Dharamveer Grewal
Dharamveer Grewal

Reputation: 135

'Undefined' passed from parent to child component in React?

I have the following code with a parent and a child class, The parent class is the Container and the child presents the results on the screen.However I am unable to pass values from parent to child. Whenever I try to pass the value, I get undefined

Parent Class

class Container extends React.Component{
    constructor(props) {
        super(props);
        this.state = {course:"Commerce",grade:"10",btnState:"Add"}
}
render(){

        return (
          <Presentation course={this.state.course} grade={this.state.grade} btnState={this.state.btnState}
           />
        );
    }
}

Child Class

class Presentation extends React.Component {
     debug(){
       alert(this.props.course)
     }
    render () {
  return (
    <div>

        <form>

            <input type="text" value={this.props.course} /><br/><br/>
            <input type="text" value={this.props.grade}  /><br/><br/>
            <input type="reset" id="addCourse" value={this.props.btnState} 
  onClick={this.debug.bind(this)}/>
            </form>
    </div>
  );
}
   }

The Rendering

ReactDOM.render(
      <Presentation />
      , 
      document.querySelector("#container1")
    );

The form is rendering correctly but the values are not being passed into the child from the parent. alert(this.props.course} gives undefined

Upvotes: 0

Views: 423

Answers (1)

Thomas Upton
Thomas Upton

Reputation: 1899

You say you have a container component, but you're directly rendering the child component Presentation.

ReactDOM.render(
      <Presentation />
      , 
      document.querySelector("#container1")
    );

Try rendering the container, e.g.

ReactDOM.render(
  <Container />,
  document.querySelector("#container1")
);

And see if that renders the container, creates state, and passes the expected props to Presentation.

Upvotes: 3

Related Questions