Learn

Take a look at the Button component class.

Notice that on line 8, Button expects to receive a prop named text. The received text will be displayed inside of a <button></button> element.

What if nobody passes any text to Button?

If nobody passes any text to Button, then Button‘s display will be blank. It would be better if Button could display a default message instead.

You can make this happen by giving your component class a property named defaultProps:

class Example extends React.Component { render() { return <h1>{this.props.text}</h1>; } } Example.defaultProps;

The defaultProps property should be equal to an object:

class Example extends React.Component { render() { return <h1>{this.props.text}</h1>; } } // Set defaultProps equal to an object: Example.defaultProps = {};

Inside of this object, write properties for any default props that you’d like to set:

class Example extends React.Component { render() { return <h1>{this.props.text}</h1>; } } Example.defaultProps = { text: 'yo' };

If an <Example /> doesn’t get passed any text, then it will display “yo.”

If an <Example /> does get passed some text, then it will display that passed-in text.

Instructions

1.

Click Run.

What a sad, textless button! :(

2.

On line 15, give the Button component class a defaultProps property. Make this property equal to an object.

Give the defaultProps object one property, so that text‘s default value is equal to 'I am a button'.

The button’s appearance should change. Much better!

3.

In the ReactDOM.render() call, give <Button /> the following attribute:

text=""

Your new prop should override the default, making the <button></button> sad again :(

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?