0

I'm working on a React project and attempting to use defaultProps with a functional component. However, when I don't explicitly pass props, the default values are not being applied.

Course component:

function Course(props) {
    return (
      <div className={Styles.card}>
      <img src={props.image} alt="" />
      <h2>{props.name}</h2>
      <p>{props.price}</p>
    </div>
    );
}

Course.defaultProps = {
    image: image1,
    name: "Default Course",
    price: "1 Like + 1 Subscribe",
};

export default Course;

App component:

function App() {
    return (
        <>
            <Course name="HTML" price="$200" image={image1} />
            <Course name="CSS" price="$250" image={image2} />
            <Course name="JavaScript" price="$500" image={image3} />
            <Course />
        </>
    );
}
export default App;

1 Answer 1

1

Because Component.defaultProps is now deprecated and the React team recommend using the JavaScript defaultValue instead. This question is similar to the question asked here:

Unable to render/see the default value of a prop in React

In your case, you would need to get rid of the Course.defaultProps and adjust your code as follows:

function Course({image = image1, name = "Default Course", price = "1 Like + 1 Subscribe"}) {
    return (
      <div className={Styles.card}>
      <img src={image} alt={name} />
      <h2>{name}</h2>
      <p>{price}</p>
    </div>
    );
}

export default Course;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.