The Card
component we previously wrote is impractical because it does not allow for text changes. Creating a new component for each specific Card
block is not a good idea, as the data is often substituted dynamically.
You can send data to components using props:
See the Pen js_react_props by Hexlet (@hexlet) on CodePen.
As you can see, we pass props from the outside as attributes in HTML, accessible inside the component from the props
object. And this transfer of input data shouldn't be new to you anymore.
Built-in components take props, such as className
and others, as input in the same way:
const vdom = (
<div className="row">
<div className="col-6">
<HelloMessage name="Kate" />
</div>
<div className="col-6">
<HelloMessage name="Mark" />
</div>
</div>
);
Props are a simple mechanism for transferring data to components, and it doesn't cause any difficulties. The main thing to remember when working with props is that we can't change them. It is so firstly because of the way React works. It won't get you anywhere. And secondly, React has an entirely different mechanism for dealing with the changeable state, which we'll look at later.
Spread operator
When working with props, we often have to pass many parameters, or these parameters are present in the code as an object. In this case, you can simplify the transfer by using a spread operator:
const params = {
className: 'row',
title: 'name',
};
const name = 'Eva';
const vdom = <div id="container" {...params}>
Hello, {name}
</div>;
The code above is equivalent to the following example:
const name = 'Eva';
const vdom = <div id="container" className="row" title="name">
Hello, {name}
</div>;
Default Props
Developers face another challenge when setting default values for props, especially when some props are not passed.
It is easiest to set them right inside the render
function using this approach:
const title = this.props.title || 'hi!';
It will work but could potentially lead to performance problems and other issues. We will cover the topic of productivity in one of the last lessons.
React provides a way to set default props values. Example:
class Header extends React.Component {
render() {
const { text } = this.props;
return (
<h1>{text}</h1>
);
}
}
Header.defaultProps = {
text: 'Hello, world!',
};
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.