The Card
component we wrote earlier is useless in practice because it doesn't allow you to change texts. And it's not a good idea to create your own component for each specific Card
block. Not to mention the fact that most often this is simply impossible, because the data is substituted dynamically.
You can send data to components, and this is done using props:
See the Pen js_react_props by Hexlet (@hexlet) on CodePen.
As you can see, from the outside props are passed as attributes in HTML, which are 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 very simple mechanism for transferring data to components, and it usually doesn't cause any difficulties. The main thing to remember when working with props: is that they can't be changed. Primarily because of the way React works, it simply won't get you anywhere, and second, React has an entirely different mechanism for dealing with changeable state, which we'll look at later.
When working with props, it's often necessary 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>;
Another challenge developers face is setting default values for props (for cases where 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!';
This will work, but could potentially lead to performance problems, as well as other issues. The topic of productivity will be covered 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!',
};
The Hexlet support team or other students will answer you.
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.
Programming courses for beginners and experienced developers. Start training for free
Our graduates work in companies:
From a novice to a developer. Get a job or your money back!
Sign up or sign in
Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.