Props
Props enable reusability of components by allowing configuration.
To assign props to an element, you add it as you would add attributes to an HTML element.
<Greet name="Mark" />
<Greet name="Robin" />
<Greet name="Oscar" />
To read the props inside the component, you need to pass it as a parameter.
import React from "react";
const Greet = (props) => {
return <h1>Hello {props.name}!</h1>;
};
export default Greet;
Destructuring Props
Instead of repeating props.name
every time, we can destructure the props to make the code cleaner.
import React from "react";
const Greet = ({name}) => {
return <h1>Hello {name}!</h1>;
};
export default Greet;
Passing children element props
We can also pass in child JSX elements or dynamic HTML content as props in between the component - as follows:
<Greet name="Mark">
<p>Test Child!</p>
</Greet>
In the component:
import React from "react";
const Greet = ({ name, children }) => {
return (
<div>
<h1>Hello {name}!</h1>
{children}
</div>
);
};
export default Greet;
Props with a Class Component
For a class component, the passing of props works in a similar way, except that in the component you have to use the this
keyword:
import React, { Component } from "react";
class Welcome extends Component {
state = {};
render() {
return <h1>Welcome to this class component, {this.props.name} </h1>;
}
}
export default Welcome;
Immutability of Props
Props are immutable, their value cannot be changed from within the component. Attempting to change the props results in TypeError: Cannot assign to read only property.
Last updated