Why do we define defaultProps outside of a class component not inside it?
https://www.codecademy.com/courses/react-101/lessons/this-props/exercises/defaultprops
Why do we define defaultProps outside of a class component not inside it?
https://www.codecademy.com/courses/react-101/lessons/this-props/exercises/defaultprops
You could if you wanted to:
class Button extends React.Component {
constructor() {
super()
this.text = 'I am a button'
}
render() {
return (
<button>
{this.text}
</button>
);
}
}
In any case, the original example is not how props are usually defined anyways, but it’s just there to help you understand the concept of props (aka properties) and defaultProps. As the name implies, defaultProps are the props that the component will inherit by default (as in, when the props aren’t otherwise defined in the rendering of the component). For example, the usual application of props on a button would be more like:
import React from 'react';
import ReactDOM from 'react-dom';
class Button extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<button>
{this.props.text}
</button>
);
}
}
class Form extends React.Component {
render() {
return (
<form>
<label for='password'>Password</label>
<input type='password' id='password'></input>
<br />
<Button text='Submit' />
</form>
)
}
}
ReactDOM.render(
<Form />,
document.getElementById('app')
);
Here, I’ve created another component called, Form, and I’ve used it to create a form with the Button component inside it. Inside Form’s call to render Button, I passed down the prop of text as ‘Submit’. So when it all renders, the Button receives a prop of text from Form and when it renders, its’ text becomes ‘Submit’ because I make the inner content of it equal to this.props.text