Problem: I have a function that makes several team cards for me, so as not to have to make twenty different pages I have decided to create a new component that is the react
same for all and that allows me to not have to create these pages, the problem I have is when I try to pass both with Link
from react-rooter-dom
and with the tag button
, since I want to pass a property of the state
specific to the other component.
Component 1 starting component 2
const equiposJSx = [];
this.state.equipos.forEach((equipo, index) => {
equiposJSx.push(
<div className="card-container" key={this.state.equipos.Equipo}>
<div className="image-container">
<img alt="foto" src={this.state.escudos[index].Link}></img>
</div>
<div className="card-content">
<div className="card-title">
<h3>{equipo.Equipo}</h3>
</div>
</div>
<button
class="btn btn-success"
onClick={() => {
this.setState({ isOpen: true });
this.handleEquipoActual(equipo.Equipo);
window.location.href('/Plantilla');
Plantilla.handleEquipo(this.EquipoActual);
}}
>
ver más
</button>
</div>
);
});
Component 2
import React, { useState } from "react";
import axios from "axios";
export default class Plantilla extends React.Component {
state = {
loading: true,
Equipo: "",
Jugadores: [],
};
componentDidMount() {}
handleEquipo(string) {
this.setState({
Equipo: string,
});
}
async componentDidMount() {
const url =
"http://localhost:8000/api/Jugadores/?search=" + this.state.Equipo;
console.log(this.state.Equipo);
const response = await axios.get(url);
const data = await response.data;
this.setState({ Jugadores: data });
}
The button can be wrapped with the component
Link
, this in order to call the functions of the buttonComponente uno
when clicking on the linkver más
:In addition, it is specified to the component
Link
that parameters are sent in theURL
, this in the propertyto
, in this case the parameterequipo.Equipo
that is the one that needs to be passed asprops
to the componentPlantilla
, this process is known asDynamic Routing
:Then, within it
Componente 1
, in the methodreturn
, you would have to add the componentRoute
that is going to render the componentPlantilla
(you may already have it), there you extract the parameter that comes in the propertyto
ofLink
, the dynamic part of theURL
and configurePlantilla
so that you receive theprop
equipo
:Please try the following:
Component 1
Component 2
Hope this answer is helpful.