In React, when we pass our data around itโs passed around using State and Props. The direction in which data flows is top to bottom.
Props are immutable meaning we cannot mutate props in any fashion. We simply receive them in our components and use them to display data to the user. Remember the idea here is to build out User Interfaces. How do we interface with our users, and Props are that data that we pass around that our users will interact with.
Take the following example:
const MyComponentsWithProps = props => {
return <h1>Hello, my name is {props.name}</h1>;
};
When we use the component above, weโll pass it some props so that we can print our name using that component. Because of reusability, I can now use this component in multiple instances:
<MyComponentsWithProps name="Fred" />
Displays "Hello, my name is Fred." And we can use it in other instances.
<MyComponentsWithProps name="Barney" />
<MyComponentsWithProps name="Bam-bam" />
<MyComponentsWithProps name="Bety" />
<MyComponentsWithProps name="Wilma" />
<MyComponentsWithProps name="Pebbles" />
All of these components will display their name prop respectively. Each will have their own object created through the react ecosystem as we pass props DOWN to them that will look like this.
Using props to get to know Bart
BartProfile objectbart and mount it up<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting to know Bartholomew J. Simpson</title>
</head>
<body>
<div id="root"></div>
// Step 1
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script type="text/babel">
// Step 3
const BartComponent = props => {
return (
<div>
<h3>Name: {props.bart.name}</h3>
<p> age: {props.bart.age}</p>
<p>Identity: {props.bart.identity}</p>
<p>Best Friend: {props.bart.best_friend}</p>
</div>
);
}
const App = () => {
// Step 2
const BartProfile = {
name: "Bartholomew Jo-Jo Simpson",
identity: "The troublemaker of the Simpson family.",
age: "10 (2 years and 38 days older than Lisa)",
best_friend: 'Milhouse Van Houten',
}
return
<div>
// Step 4
<BartComponent bart={BartProfile}>
</div>
}
ReactDom.render(<App />, document.getElementById('root'));
</script>
</body>
</html>
Build out a component called <MeComponent /> that will depend on Props being passed down to it. Those fields on the Props object will be descriptors about who you are as a person. Render out your name, age, location, favoriteBook, favoriteBand.