List With Modification Button For Each Element
I have a React Redux app that shows a list of cars parked in a chosen parking, but not all cars, only those with a property called parked=true.
I'm using APIs to modify and get elements from the database, now I need a PUT request to modify the state of each car to parked=false and so remove it from the list. I already have the PUT function (which I linked below).
My problem is that the function needs the ID of the element and I don't know how to pass it to the function.
Here's my code (voiture means car):
this is my function in my actions.js
export const ParkedModifié =(voiture) => ({
type: VOITURE_MODIFIED,
voiture
});
//PUT request
export const notParked = (id)=>{
return(dispatch)=>{
return requests.put(
`/voitures/${id}`,
{
parked: false
}
).then(response => dispatch(ParkedModifié(response)))
}
}
and here's my carList.js
return (
<div className="card mb-3 mt-3 shadow-sm">
{ voitureList.map(voiture => {
return (
<div className="card-body border-bottom" key={voiture.id}>
<p className="card-text mb-0">
{voiture.matricule}
</p>
<p className="card-text">
<small className="text-muted">{timeago().format(voiture.gareele)}</small>
</p>
<Button color="danger" onClick={this.onSubmit}>Change</Button>
</div>
);
})}
</div>
)
}
Answer
Following pattern is what I always use. That way, you don t pass a function with different reference each time. In this case which would lead your Button
component to rerender for nothing, whenever this parent component renders.
So what we do here is to pass onSubmit
and read from 'data-' attribute inside.
onSubmit = event => {
const id = event.currentTarget.getAttribute('data-id')
// use id however you want
}
return (
<div className="card mb-3 mt-3 shadow-sm">
{ voitureList.map(voiture => {
return (
<div className="card-body border-bottom" key={voiture.id}>
<p className="card-text mb-0">
{voiture.matricule}
</p>
<p className="card-text">
<small className="text-muted">{timeago().format(voiture.gareele)}</small>
</p>
<Button
color="danger"
data-id={voiture.id}
onClick={this.onSubmit}
>
Change
</Button>
</div>
);
})}
</div>
)
}
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM