React Props (short for properties) are a mechanism for passing data from one component to another in React. They are used to transfer information from a parent component to its child components, making components reusable and dynamic.
Immutability
Props are immutable, meaning they cannot be modified by the receiving component. This ensures that data flows in a single direction (from parent to child), which is a core concept in React’s architecture.
Passing Props
Props are passed to components similarly to how attributes are added to HTML elements.
<ChildComponent name="John" age={30} />
Here, name
and age
are props being passed to ChildComponent
.
Accessing Props
In the child component, props are accessed via the props object. For a functional component, this looks like:
function ChildComponent(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
}
Default Props
You can set default values for props through the defaultProps property of a component class.
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
class HelloMessage extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
HelloMessage.defaultProps = {
name: 'weiy.cc'
};
const element = <HelloMessage/>;
ReactDOM.render(element, document.getElementById('root'));
Prop Types
Prop types can be defined using the prop-types library to enforce the types and shapes of props, which helps catch bugs and improve code clarity:
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
function ChildComponent({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
ChildComponent.propTypes = {
name: PropTypes.string,
age: PropTypes.number
};
ReactDOM.render(<ChildComponent name="weiy" age={12}></ChildComponent>,
document.getElementById('root'));
.
Props are fundamental to React’s design, enabling components to be more dynamic and reusable while maintaining a clear and predictable data flow.