Where HTML elements have attributes, React components have props
A prop is any data passed into a React component. React props are comparable to HTML attributes.
Where HTML elements have attributes, React components have props.
Props are written inside component calls, and use the same syntax as HTML attributes — prop="value".
In React, dataflow is unidirectional: props can only be passed from Parent components down to Child components; and props are read-only.
Let’s open index.js and give our <App/> call its first prop.
Add a prop of subject to the <App/> component call, with a value of Clarice. When you are done, your code should look something like this:
ReactDOM.render(<App subject="Clarice" />, document.getElementById('root'));
Back in App.js, let's revisit the App function itself, which reads like this (with the return statement shortened for brevity):
function App() {
const subject = "React";
return (
// return statement
);
}
Change the signature of the App function so that it accepts props as a parameter, and delete the subject const.
Just like any other function parameter, you can put props in a console.log() to print it to your browser's console. Go ahead and do that before the return statement, like so:
function App(props) {
console.log(props);
return (
// return statement
);
}
Save your file and check your browser's JavaScript console. You should see something like this logged:
Object { subject: "Clarice" }
The object property subject corresponds to the subject prop we added to our <App /> component call, and the string Clarice corresponds to its value. Component props in React are always collected into objects in this fashion.
Now that subject is one of our props, let's utilize it in App.js.
Change the subject constant so that, instead of defining it as the string React, you are reading the value of props.subject. You can also delete your console.log() if you want.
function App(props) {
const subject = props.subject;
return (
// return statement
);
}
When you save, the app should now greet you with "Hello, Clarice!". If you return to index.js, edit the value of subject, and save, your text will change.