How does React “props” work?

Components in React are used to translate raw data into html. Props (short for properties) in React are a set of data that can be transferred from a parent component to its child component and then can be used by a render() function to generate the view. The important thing to remember about props is that they are immutable. This means that the parent component can send whatever prop values he likes to a child component, but the child cannot modify them by itself. Props are plain JavaScript objects. By changing them, we are triggering render() function to update the view.
It’s going to look a lot like passing or setting an attribute on the standard html element. They are available as a property and they are accessed through “this.props”. Using props gives you the ability to read and use every kind of data; you can drop text or even entire components.
Transferring and viewing props – If you want to access any named attributes just use “this.props”, if any nested elements – “this.props.children”. To drop some text into the DOM tree, you need to surround JavaScript inside your JSX expression in curly brackets.
We can also define the property type that we are expecting using something called “propTypes,” for example, as a string or a number and many others (for more read the documentation). This is called “props validation” and it’s helpful when your application grows. React.PropTypes can be used to make sure the data received are valid. There is an option to make some “defaultProps” with some key and a default value assigned to it.


Leave a Reply

Your email address will not be published. Required fields are marked *