A color must be removed from the palette when the user clicks on a swatch's delete button. Though the action is triggered on a child component, it is the parent App
component that must change. The color must be removed from its state. You achieve this cross-component behavior through props.
The parent component first defines a function that removes a named color from its array and updates its state through the setter:
function App() {
// ...
const removeColor = name => {
setColors(colors.filter(color => color.name !== name));
};
// ...
}
Removing is done by keeping only the colors that don't have the name of the color to remove. You do not use delete
operator. That would involve mutating state, and mutating state is forbidden in a React app.
Then you pass this function to each swatch as another prop:
function App() {
// ...
return (
<div className="App">
{
colors.map(color =>
<Swatch
key={color.name}
name={color.name}
hex={color.hex}
remove={removeColor}
/>
)
}
</div>
);
}
Note that the name of the prop is remove
, while the name of the local function is removeColor
. As with regular function calls, the names of formal parameters and variables sent as actual parameters do not need to match.
Inside Swatch
, you unpack the remove
function from the bundle of props and call it when the delete button is clicked:
export function Swatch(props) {
const {name, hex, remove} = props;
// ...
return (
<div className="swatch" style={style}>
{/* ... */}
<button
className="delete-button"
onClick={() => remove(name)}
>✖</button>
</div>
);
}
Note that you can't write onClick={remove}
. In this shorter form, the parameter to the callback is implicitly an event object. But you need to pass the name of the color.