Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of React JS and exploring one of its powerful features - Default Props. Let's get started! 📝
Before we dive into default props, let's quickly recap what props are. In React, props (short for properties) are a way to pass data from a parent component to a child component. They allow us to customize the behavior and appearance of a child component. 💡
Imagine you're building a component that can display a user's name. Sometimes, you might not have a name to display, but you still want your component to render something sensible, like "Anonymous". That's where Default Props come in handy.
To set a default prop for a component, you can use the defaultProps property in the constructor of your component. Here's an example:
import React from 'react';
class User extends React.Component {
constructor(props) {
super(props);
this.defaultProps = {
name: 'Anonymous'
};
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
export default User;In this example, we've defined a default prop called name and set its value to "Anonymous".
Now, let's use this User component in another component:
import React from 'react';
import User from './User';
class App extends React.Component {
render() {
return <User name="John Doe" />;
}
}
export default App;In this example, we've passed a name prop to the User component, so it will use that prop instead of the default one.
You can also set default props using the defaultProps static property instead of the constructor:
class User extends React.Component {
static defaultProps = {
name: 'Anonymous'
};
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}What are props in React JS?
With default props, you can ensure your React components always have sensible defaults. Now that you understand them, let's dive into more advanced topics in future lessons! 🚀
Remember, the key to mastering React is practice, so don't hesitate to experiment and play around with code. Happy coding! 💡