-4

I think it might be silly question to ask but trust me I didn't find an answer . I am passing down data via props to children component but I am stuck and getting error . Normally, I am passing data on form submit ( I mean when user type something and do click on submit ) I am showing data it in child component via props but on initial render of an application I am getting error props is undefined . Actually I have knowledge about defaultProps but I think it might be possible in class base component . I want to do something like defaultProps in functional Component , I am stuck could someone please help me to achieve my goal .

Code

 import React from "react";

const ViewCourse = () => {
  return (
    <div>
      {this.props.courses.map(newData => (
        <div>{newData.title}</div>
      ))}
    </div>
  );
};

export default ViewCourse;
Samri
  • 27
  • 4

3 Answers3

3

You can use classname.defaultProps to assign the initial value. Also to access props in functional component, you will have to pass it as an argument.

import React from "react";

const ViewCourse = (props) => (
  <div>
    {props.courses.map(newData => (
      <div>{newData.title}</div>
    ))}
  </div>
);

export default ViewCourse;

ViewCourse.defaultProps = {
  courses: [],
}

Milind Agrawal
  • 2,724
  • 1
  • 13
  • 20
2

You're using function component. You've to get props in the argument.

const ViewCourse = (props) => {
  // use props here.
};
Raja Sekar
  • 2,062
  • 16
  • 23
1

In functional component props is the argument.

import React from "react";

const ViewCourse = (props) => {
  return (
    <div>
      {props.courses.map(newData => (
        <div>{newData.title}</div>
      ))}
    </div>
  );
};

export default ViewCourse;