scrimba
Frontend Career Path
React basics
Meme generator
Setting state from child components
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Setting state from child components
AboutCommentsNotes
Setting state from child components
Expand for more info
App.js
run
preview
console
import React from "react"

export default function App() {
const [contact, setContact] = React.useState({
firstName: "John",
lastName: "Doe",
phone: "+1 (719) 555-1212",
email: "itsmyrealname@example.com",
isFavorite: false
})

/**
* Challenge: Move the star image into its own component
* - It should receive a prop called `isFilled` that it
* uses to determine which icon it will display
* - Import and render that component, passing the value of
* `isFavorite` to the new `isFilled` prop.
* - Don't worry about the abiliity to flip this value quite yet.
* Instead, you can test if it's working by manually changing
* `isFavorite` in state above.
*/

let starIcon = contact.isFavorite ? "star-filled.png" : "star-empty.png"

function toggleFavorite() {
setContact(prevContact => ({
...prevContact,
isFavorite: !prevContact.isFavorite
}))
}

return (
<main>
<article className="card">
<img src="./images/user.png" className="card--image" />
<div className="card--info">
<img
src={`../images/${starIcon}`}
className="card--favorite"
onClick={toggleFavorite}
/>
<h2 className="card--name">
{contact.firstName} {contact.lastName}
</h2>
<p className="card--contact">{contact.phone}</p>
<p className="card--contact">{contact.email}</p>
</div>

</article>
</main>
)
}
Console
/index.html
-6:28