Props Are Read-only
Props are read-only values inside a component. A component can read a prop but cannot change it.
Read a prop
Reading leaves the prop unchanged.
props.priceCompute a new value
total is a new const. The prop stays unchanged.
const total = props.price + 2Show the result
The paragraph shows the computed total.
return <p>Total is {total} dollars.</p>Example
function Price(props) {
const total = props.price + 2
return <p>Total is {total} dollars.</p>
}
export default function App() {
return <Price price={10} />
}
Key points
- Reading a prop never changes the passed value.
- A component can store a prop value in a new const.
- A component can compute a new value from a prop.
- A component must never assign a new value to a prop.
In this example, Price takes props as its first parameter. Price reads props.price and adds 2. The result goes into a new const named total. Price never assigns to props.price. The page shows Total is 12 dollars.
Note
A new const holds the computed result. The prop stays unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What can a component do with a prop value?