Props in React
In our previous chapters and examples, we were introduced to React components and we also briefly saw how data can be passed from a parent component to a child component. This is a simple implementation of props.
Props in React is a way of passing data from parent to child. Let's look at a simple example where we pass a name to a component that renders a message. Setting props in our JSX is similar to setting an attribute in XML or HTML. Here's an example of sending props to the HelloMessage
component:
function App() { return ( <div> <HelloMessage name="John" /> </div> ); }
The props that have been sent to a class component can be accessed using this.props
. Here's an example of the HelloMessage
component receiving name
as a prop:
import React, { Component } from "react"; export class HelloMessage extends Component { render() { ...