React - Passing Data Via Props

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

TABLE OF CONTENTS

Intro to Props ………………………………………………………………………………………………………….. 3

Planning …………………………………………………………………………………………………………………….. 4

Using Components & Props ………………………………………………………………………………………. 5

(ex) Name Tag Props …………………………………………………………………………………………………. 6

Name Tags and Collectors ……………………………………………………………………………………….. 7

Importing Name Tag …………………………………………………………………………………………………. 8

Three-Car Pile Up Project …………………………………………………………………………………………………. 9

Data Flow for Three-Car Pile Up ……………………………………………………………………………………….. 10

Parent Component Breakdown ……………………………………………………………………………………….. 12

Destructuring Props …………………………………………………………………………………………………. 14

Updating State ……………………………………………………………………………………………………………. 16

The Blueprint for Child Component(s) …………………………………………………………………………….. 17

Passing Props to Child Component ……………………………………………………………………………. 18

Mapping Over Arrays …………………………………………………………………………………………………. 19

Conclusion ……………………………………………………………………………………………………………………... 22
INTRO TO PROPS

Props - what you need to know:


● Short for property
○ Think about things you would inherit from your parent.
■ Last name
■ Eye color
■ Height
■ Etc

● An object with a key:value pair. (🗝: 💲)


● Key is name you give it
● The value you give it is the props
● aka Data that can be passed from one component to another as a parameter.
● Data passed can be many things:
○ Strings
○ Functions
○ Numbers
○ Etc
● Information flows down hill. The parent passes to the child. I have related this to a
3-car pile up you’ll hear more about later (there is also a visual of this on page 21.)
● When I am building out an app,
○ I first map out what components I’m going to have
○ who the parent is (parent component)
○ what attributes(props) they will be passing down
○ Who the children are (child components)
○ And what the layout will look like - where will the components live and which
components will go where.

Having a visual of it before I start coding really helps me to understand


where everything is coming from and where to pass props.

Understanding props can be one of the hardest concepts to wrap your


mind around (at least it was for me.)
I have included several visuals to help you understand props better.
PLANNING

Before doing any coding, we need to evaluate what our project is asking from us
and map it out.

This will allow us to know:


● The main component (that will house everything else)
● The parent component (that will house the data, set up state, and set up
props to be passed)
● The child components (that will take in props)
● Determine where changes are going to be made

The parents <Main Component>


have all the
info. They will Renders everything
pass all their
genetics This would be like the master
(props) to the bedroom of the house - only
<Parent Component>
children. the parent belongs there.

The parents CH CH CH

house the Each child has access to the


children but Parent’s data but will present
not in the their own information derived
master BR) from that data.

<CHILD DETAILS>
Each Child Detail card will
ONE TWO THREE display different aspects of the
child.

ONE TWO THREE


USING COMPONENT & PROPS

❓How do we use components and props together?


Imagine a new neighborhood or housing development being built in your
community.

🏡🏡 🏡
🏡
📫
📫 📫 📫
📫
🏡
Components are like the blueprints for these houses. Instead of
creating a new blueprint for each house (when they all look the same),
they create one and use it over and over again.

Props are the items unique to each house. They have a key:value pair.
Instead of that information being hard-coded in (predetermined), the
builder will pass along the component (house) along with the props to
the new owners and allow them to fill out that information unique to
their needs/wants.

address: ‘ ‘ ,
doorColor: ‘ ‘ ,
familySize: 0,
dog: false

Each family has a house(component) with properties to use.


(example) NAME TAG PROPS
NAME TAGS & COLLECTOR

EXPORTING

Creating the function with props and exporting it.

function NameTag (props) { // NameTags will take in the individual props added by each person
return (
<div>
<h2>Name: {props.name}</h2>
<h3>Age: {props.age}</h3>
<h3>Job: {props.job}</h3>
</div>
)
}
export default NameTag

The NameTag component is then imported where it needs to be used and can
be reused over and over again as it is rather than recreating it each time. We can
simply input the values we want for the props.
IMPORTING NAME TAG

import NameTag from ‘./components/NameTag’;

function NameTagCollector () {
<NameTag name = “Katrina”, age = 32, job = “SL”/>
<NameTag name = “Mel”, age = 25, job = “SL”/>
<NameTag name = “Taja”, age = 24, job = “TL”/>
}

Here, this information is hardcoded. (Like writing it on a name tag and slapping it
on your shirt.)

If there is data set up, when the <NameTag /> is added to the
<NameTagCollector/> and the <NameTagCollector /> is added to the <App />,
then the information from data will be pulled in and rendered.

<App />

Data is housed
<NameTagCollector />
and passed down.

<NameTag />
THREE-CAR PILE UP PROJECT

You will see me relate a lot of things to mass traumas, car accidents, EMS
calls, etc. That comes from a lifetime in the medical field and has helped
me learn many of the webdev concepts we study.

For passing props, you’ll learn about a three-car pile up and how EMS
would store and share the information from the call. Be sure to check out
the Three-Car Pile Up project in code-pen to see the full breakdown of
the components.

Component layout:
1. Index.js = renders <DailyReport /> (aka <App />)
2. <DailyReport />
a. Main Component
b. Houses <CallLog/>
3. <CallLog />
a. Parent component
b. Houses data and maps through it to display:
c. <PatientCard />
i. Receives props from <CallLog />
4. <PatientCard />
a. Displays several components that make up the <PatientCard/>
i. <PtBio /> (patient info)
ii. <Treatment /> (what was done)
iii. <PainScalePoints /> (has buttons to + /- pain)
iv. <ResourceList /> (who showed up)
b. Passes props given by <CallLog />
DATA FLOW FOR THREE-CAR PILE UP

React only flows in 1 direction - downward. So if I wanted the data to be


accessible to all my components, it would need to reside in the <App />
component and flow down through props. This is known as prop-drilling
(as mentioned earlier.)

In the image below, there are 7 components.


Daily Report: (also known as the <App />)
Components can be named anything. Convention says the component that
renders everything should be called <App />. Kind of like a table of contents.
That <App /> is then appended to the root element of the entire project.

In this case, we are going to rename the <App/> to be <DailyReport />. It is the
main component that will render everything.

In EMS, there is a Daily Report that is given. That <DailyReport /> component (or
App) holds all the calls of that day- CallLog. The <CallLog /> component holds all
the data. Since the CallLog is housed in the DailyReport (App), the data can be
accessed by all the other components through props.

You have to dig a little deeper in the CallLog to get to the information about each
call. But on the Daily Report (App), an EMS provider could list many CallLog
components

��
<DailyReport>
<CallLog>
<PtCard/>
<PtCard/>
</CallLog>
</DailyReport>
PARENT COMPONENT BREAKDOWN

If you take a look at <CallLog /> being housed in the <DailyReport(App) />, there is no mention
of data or props. Just the component.

If you want to see what happened on the CallLog, you have to go TO the CallLog

<CallLog /> is also a component. (It is the parent component that will be passing the
information down.)

At the beginning of every shift, The DailyReport is empty and the medic has an empty CallLog
waiting to have values added to it. The CallLog has many properties(props) but no hardcoded
value. It’s a standardized form of information that is used for every patient. With each new
patient, new values are imputed.

Because the CallLog is a component, it only has to be created once and can be reused as
many times as needed without having to recreate it.

(Refer back to the IMG-1 if you are still having a hard time understanding components
and props)

Call Log
The CallLog brings in the data from the call(patientData.) Rather than add data to every
component that will need it, we house it in a parent component(CallLog), render it in <App />
(DailyReport) and then every component has access to it.

From there, we pass all the properties down to each component that needs them.

❓But what’s really happening in the CallLog?


Let’s take a look and break it down.
You’ll notice in step2, that the data is set as a variable, but there hasn’t been a
function created to change the data. That’s because in this case, we aren’t changing
any of the data. So we won’t need a function to change it.

As you see, there is a lot happening in this tiny little component. But that’s how it
goes even on an emergency call. Someone calls 911 and even though the event is
contained to one intersection or one house in a large area, there are a lot of people,
resources, and moving parts involved.

Now the data has been pulled in. A new PatientCard is waiting to be created for
each new patient.

Edit: we don’t actually need useState here since we aren’t


changing the state. We can use it, but it doesn’t really
change anything.

We can simply write const data = patientData;


DESTRUCTURING PROPS

❓What does the PatientCard look like?

😷 Each PatientCard will hold a lot of properties (props) waiting for values to be added. Each
PatientCard will look the same. Only the values will change.

🚺🚹 Patient Bio (name/age/gender)


🩹🩹🩹 Treatment (including complaint and results of treatment)
🙂😢😭 PainScale With the ability to increase or decrease after treatment.
🚔🚒🚑 A Resources List of resources that showed up to help.
👮👮👮 Resource Card (info about each resource)

Before we can create any of the components included on the PatientCard, we have to pay
attention to a few aspects. Particularly this line:

Component name

const PatientCard = ({propsFromPtCard}) => { }

Tells us to give the


components access to
the props

In this example above, we have destructured propsFromPtCard. This means, each time we
use propsFromPtCard, we won’t have to add props. in front of it. It’s a small change but it
saves us a few key-strokes.

We could have written it as


const PatientCard = (props) => {}
Instead of having to write props.propsFromPtCard every time we pull down props, we now only
have to write propsFromPtCard.

While that isn’t a big change, writing it with (props) means we have to add props. Everytime we
are pulling down props. (props.propsFromPtCard.whatever)

Next, let’s look at the components listed that will be added/created. We aren’t changing the data
that is accessible on the parent component - CallLog. That is the information we are given and
will remain as it is.

But, the PainScale component has the ability to update the patient’s pain level.

<PatientBio /> (name/age/gender)


<Treatment /> (including complaint and results of treatment)
<PainScalePoints /> with the ability to increase or decrease after treatment
<ResourceList /> resources that showed up to help
<ResourceCard /> (info about each resource)

❓ So what does that mean?


We need to set the patient’s pain level to a variable and create a function to allow
us to update it.

Let’s take a look at that section as well.


UPDATING STATE

Now all we have to do is set up the components we want to add to the <PatientCard />
component.

We will:
● add them in the order we want them to appear,
● pull down props, and
● get the appropriate date using dot notation.

(ex)

🚺🚹 PtBio (name/age/gender)

(Note: pt is short for patient)


THE BLUEPRINT FOR THE CHILD
COMPONENT(S)

This is the same for <Treatment />, and <ResourceList />.

But remember, we will be updating the patient’s pain level after we’ve administered treatment. It
will either remain the same, increase, or decrease. (Hopefully it doesn’t increase but it could. 😉)

Let’s go back to the functions we created to update the patient’s pain.

const incrementPain and const decrementPain

When we add the <PainScalePoints> component, we will pull in these functions as well as the
patient’s pain level recorded in data. It will look like this:

<PainScalePoints
incrementPain = {incrementPain}
decrementPain = {decrementPain}
Pain = {pain}
/>
PASSING PROPS TO CHILD
COMPONENT

The only thing left to do is export the PatientCard (since we’ve already imported it to the
CallLog.) Otherwise, we will get errors.

When a medic fills out a PatientCard, she will go down the list to make sure she hasn’t
missed inputting any of the values(props) or points on the list.

With <PtBio /> component, pull in props and then set up the component how you want it
presented (presentational component.)
MAPPING OVER ARRAYS

<Treatment /> and <ResourceList /> are different from the <PtBio /> component.

Take a look at the patientData:

export const patientData = [


{
name: "Jane Doe",
age: 32,
gender: "female",
complaint: ["headache, ", "short of breath "],
treatments: [{ type: "O2", amount: "2L", result: "sats at 97%" }],
painScale: 3,
resources: [
{ rsType: "FD", type: "Engine", unit: "31", chief: "Tucker" },
{ rsType: "PD", type: "HP", unit: "50", chief: "Jones" },
{ rsType: "EMS", type: "Medic", unit: "21", chief: "Tucker" }
]
}
]

You’ll notice that complaint, treatments, and resources all contain arrays.

Treatments and resources contain an array of objects.

We will have to address these differently than we did the PtBio where we were simply
addressing individual items.

We will be putting the complaint array on the <Treatments /> component rather than it’s
own component since these two depend on each other. This is strictly a personal choice.
Complaints could have had its own card but it didn’t seem necessary.

We will map over each of these and return a new array with each item.
The difference is, complaint is returning an array of items, not objects. So
presentationally, it will look differently.

{complaint.map((c, index) => {


return <h3 key = {index} > {c}</h3>;
}

Nothing fancy. We map over the complaint array, stopping at each complaint ( c ) along
the way, creating an index and returning that complaint ( c ) with a key index and <h3>
tag.

But, the treatments array returns an array of objects which means we need to list those
key:value pairs and use dot notation to pull in the values of each.
The ResourceList is also an array of objects that when mapped over will return a <ResourceCard
/> that includes all the key:value pairs of the object.

It will look like this:

const ResourceList = ({ resources }) => {


return (
<>
<h2> Resources: </h2>
{resources.map((resource, index) => (
<ResourceCard
key = {index}
rsType = {resource.rsType}
type = {resource.type}
unit = {resource.unit}
chief = {resource.chief} />
))}
</>
)};
export default ResourceList;

Finishing up the components is the ResourceCard. The props are passed in there as well, either
by adding (props) as the parameter or destructuring the items that will be using props:

rsType
Type
Unit
Chief

This is mostly a presentational component.


There is no mapping because the mapping already occured
with the ResourceList component.
CONCLUSION

Now our DailyReport(<App />) is complete (aside from styling. We’ll cover
that in a later lecture/workshop..)

But, there are 7 components in this App that can be reused over and over
again. If the Emergency Room staff wanted to incorporate a DailyReport
into their files, they wouldn’t need to recreate these components, they
could simply borrow ours.

They could borrow it as a whole or whichever piece they wanted to reuse.

Keeping components in their own separate files also makes it easier to


debug.

Be sure to fork the repo. Play in it. Break it (that’s the best way to learn.)
Add some more components if you want. Have fun.

Study the diagrams and images so you have a clear understanding of


what’s happening in the code.

If you have any questions, feel free to reach out to me anytime.

🔗 Github link to The Tale of the Three-Car Pile Up


CodeSandbox link

You might also like