简体   繁体   中英

How to pass down custom props on initial render

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;

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: [],
}

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

const ViewCourse = (props) => {
  // use props here.
};

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM