Reputation: 86
How can I can call a function that is in the parent component (App) from a child component (Card)?
Card component renders one item (CHILD)
const Card = (props) => {
return (
<div style={{margin: '1em'}}>
<img alt="Profile" width="75" src={props.avatar_url} />
<div style={{display: 'inline-block', marginLeft: 10}}>
<div style={{fontSize: '1.25em', fontWeight: 'bold'}}>
{props.name}
</div>
<div>{props.company}</div>
<button
//when I click here should trigger App's delete func who deletes the select item.
onClick = { () => alert()}
className="btn btn-danger btn-sm">Delete</button>
</div>
</div>
);
};
CardList component renders a list of item (CHILD-PARENT)
const CardList = (props) => {
return (
//Props.nameProp = Value {...Card} spred operator
<div>
{props.cards.map(card => <Card key={card.id} {...card} />)}
</div>
);
}
Parent component:
class App extends React.Component {
state = {
cards: [
]
};
addNewCard = (cardInfo) => {
this.setState(prevState => ({
cards: prevState.cards.concat(cardInfo)
}))
};
deleteCard = (selectedCard) => {
this.setState(prevState => ({
//array.filter creates a new array with elements who pass the foo
cards: prevState.cards.filter(card => card !== selectedCard)
}));
}
render(){
const {
cards,
} = this.state;
return(
<div className="container" style={{marginTop: 15}}>
<Form onSubmit={this.addNewCard} />
<div className="container" style={{padding: 20}}>
{
cards.length > 0 ?
<CardList cards={cards} />
:
<p>Your list is empty</p>
}
</div>
</div>
);
}
}
EXPLANATION
I want to delete a item who is in the state list but that list is in the parent component, how can I do that?
Upvotes: 3
Views: 287
Reputation: 112787
You can pass down the deleteCard
method as a prop to CardList
, and from CardList
to each Card
component and call it there.
Example
const Card = props => (
<button onClick={() => props.deleteCard(props.card)}>{props.card}</button>
);
const CardList = props => (
<div>
{props.cards.map(card => (
<Card card={card} deleteCard={props.deleteCard} />
))}
</div>
);
class App extends React.Component {
state = {
cards: [1, 2, 3]
};
deleteCard = card => {
this.setState(({ cards }) => ({
cards: cards.filter(element => element !== card)
}));
};
render() {
const { cards } = this.state;
return <CardList cards={cards} deleteCard={this.deleteCard} />;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 1