Skip to main content

Props in Function Components

Implementation of the "Employee Card".

File: src/App.tsx

import Profile from './components/ProfileClass'

const App = () => {

const person = {
id: 1,
firstname: "John",
lastname: "Doe",
job: "Developer"
}

return(
<div>
<Profile person={ person } />
</div>
)
}

File: src/components/Profile.tsx

const Profile = (props) => {

const name = `${ props.person.firstname } ${ props.person.lastname }`

return(
<div>
<h2>Profile</h2>
<h3>{ name }</h3>
</div>
)
}

Now we actually have far less code and since we don't extend something the function just takes in a normal argument (props here, but this can have any valid variable name) in which this person prop is included.

Destructuring

It's a best practice to "destructure" the incoming properties.

info

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Let's take a look on how this is done:

const Profile = ({ person }) => {

const name = `${ person.firstname } ${ person.lastname }`

return(
<div>
<h2>Profile</h2>
<h3>{ name }</h3>
</div>
)
}

We can "destructure" the incoming props object by extracting the values into new variables. So instead of using props.person we destructured the props into the { person } variable.

When passing another prop into the Component, we can destructure this as well:

<Profile person={ data } salary={ 3000 } />
...

const Profile = ({ person, salary }) => ...