1

I am following a tutorial and they set a static object named defaultprops and after setting it this.props could be used in the same component, Why is this possible, I mean what's the function of the static defaultProps and is it a bulit in function in React.

class TestComponent extends Component {
    static defaultprops = {
        food: ["goatmeat", "yam"]
    }

    render() {
        let categories = this.props.defaultprops.food.map(foods => {
            return <option key={foods}>{foods}</option>
        });

        let {test} = this.props;

        return (
            <p>
                {this.props.test}
            </p>
        );
    };
}
3

1 Answer 1

1

Default props are nice to not have to specify all of the props when passing them to a component. Just as the name implies, it allows you to set nice defaults for your props which will be used in the even that overriding values are not passed in. Please keep in mind that leaving out the prop will result in the default value being used, whereas passing in null will result in the null value to be used.

More info may be found here.

Edit
To answer the questions asked more explicitly:

This is possible because this is how React works. This is in-built functionality for programmer and logical convenience.

For the TestComponent in your example, imagine that it is used in another component. If you just use <TestComponent />, the component will have a food value of ["goatmeat","yam"]. However, you may always override this as you wish by passing in a different value for the prop when calling it. For example, you could use <TestComponent food={["cheese", "eggs", "cabbage"]}/>. This will result in this instance of the component having the food value of ["cheese", "eggs", "cabbage"].

I think it is also a good point to note that it should be defaultProps and not defaultprops because I am fairly certain capitalization matters but if anyone would like to correct me I would be happy to redact this point.

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.