Problem: I have an array of components, the thing is that I have another separate component that is a modal and I want to pass it the data of the state of the components of my array, the problem then is that if it were individually it is easy to call the state but as I can call my state if in this case it is an array of components that I have
statehook
state = {
loading: true,
Noticias: [],
showModal: false
};
handleModal = () => {
this.setState({
showModal: !this.state.showModal
});
}
array rendering
const noticiasJSX=[];
this.state.Noticias.forEach(noticia => {
noticiasJSX.push(
//Aquí quiero poder realizar { this.state.showModal? <div onClick={this.hanldeModal()} className="back-drop"></div> : null }
<div className="ml-3">
<div className="car-container">
<figure>
<p>
<img alt={noticia.foto} height="150px" width="300px" src={noticia.Foto}/>
</p>
</figure>
<div>
<div className="container">
<p>
<strong>{noticia.Titulo}</strong>
<br/>
<small><i>Equipo: {noticia.Equipo}</i></small>
<br/>
<button class="btn btn-success" onClick="">Leer más</button>
</p>
</div>
</div>
</div>
</div>
);
});
return(
<div className="container">
<div className="row">
{noticiasJSX}
</div>
</div>
);
There appear to be no write operations involved in the piece of code, only read operations.
You can create a copy of the state
Noticias
(it's what the API brings, I suppose) and work with it, declaring this copy as part of thestate
:Then to this copy
NoticiasCustom
is added the propertyshowModal
for each element:The most complicated part, when the user clicks on
div
showModal
it, here an operation is done with the operator and the sliceelipsis
method , the objective is to modify the property of the object that the user has clicked on and also, to assemble it again :showModal
Noticias[n]
NoticiasCustom
Next, the component is returned with the update of the
state.NoticiasCustom
:This way you could implement the code you propose:
Note that
showModal
it is already a property of each element of stateNoticiasCustom
, it can be used in conjunction with the ternary operator and thus return its state for each element within the loopforEach
:Below is a demo, with the implementation of the proposed code, for each element in the array
noticiasJSX
:field notes
id
for each news within the cycleforEach
, because as you mentioned in the comments, it is available.Hope this answer is helpful.