State in Function Components
File: src/App.tsx
import Profile from './components/Profile'
const App = () => {
const person = {
id: 1,
firstname: "John",
lastname: "Doe",
job: "Developer",
projects: [
{ id: 1, name: "React Frontend Development" },
{ id: 2, name: "UX / UI Design" },
{ id: 1, name: "HR Program" }
]
}
return(
<div>
<Profile person={ person } />
</div>
)
}
export default App
File: src/components/Profile.tsx
import { useState } from 'react'
const Profile = ({ person }) => {
const [showProjects, setShowProjects] = useState(false)
const name = `${ person.firstname } ${person.lastname }`
const __toggleProjects = () => {
setShowProjects(!showProjects)
}
const __renderProjects = () => {
if(showProjects) {
return(
<ul>
{
person.projects.map( (item, index) => {
return(
<li key={ index.toString() }>{ item.name }</li>
)
})
}
</ul>
)
}
}
return(
<div>
<h2>Profile</h2>
<h3>{ name }</h3>
<h4>{ person.job }</h4>
<button onClick={ __toggleProjects }>Show Projects</button>
{ __renderProjects() }
</div>
)
}
export default Profile
Breakdown
- line 1: when we use a state, we need to import a so called "Hook". In this case the
useState-hook - line 5: we fire up that hook with an initial value of
false - The hook destructures to two variables: in this case a boolean called
showProjectsand a setter function for this var:setShowProjects - You are free to choose the names of the variable en the setter, but it is usually in the format:
varandsetVar - The rest of the implementation is basically the same
- We can omit
thissince we are not working in a class - We can create functions inside of functions
- We can call
useStateas often as we like on different state variables