I have the following class that lists a series of volcanoes with code and name:
import React, { useState } from 'react';
import {useFetchVolcans} from '../assets/hooks/useFetchVolcans';
import Accordion from 'react-bootstrap/Accordion';
function Bar() {
//realizo una petición para pedir la lista de los volcanes y su codigos
const {data} = useFetchVolcans()
const [volcanInicio,setVolcanInicio] = useState()
//Aquí se modifica el código guardado si se elige uno u otro volcán de la lista
const handleVolcanInicio = (e)=>{
setVolcanInicio(e.target.value)
}
return(
<div className="barLeft">
//Aquí listo la información en un botón desplegable
<Accordion>
<Accordion.Item eventKey="0">
<Accordion.Header>Volcanes</Accordion.Header>
<Accordion.Body>
<select value={volcanInicio} onChange={handleVolcanInicio} class="form-select">
<option value="0">Elige un volcan</option>
{data.map((item) => (
<option value={item.code}>{item.name}</option>
))}
</select>
</Accordion.Body>
</Accordion.Item>
</Accordion>
</div>
);
}
export default Bar;
What I need is to send the information of the code saved in setVolcanInicio to another class and that this is done every time a volcano is chosen from the list.
In the case of having a parent component, you could declare the useState in the parent, and pass it through props, down you pass for example VolcanInicio and up you pass setVolcanInicio, Ex:
Let's say there is a parent PageHome component, somewhere in this component you will have a:
So let's say we have 2 more components, Component1 and Component2, now PageHome would look like this.
Finally, we will pass a value from Component2 to Component1 passing through PageHome, so in PageHome it would look something like this:
In Component1 we receive by props volcanInicio to show it, it would look something like this:
Now in Component2 we are going to do that when entering something in an input, the status of volcanInicio is updated, then Component2 would look like this:
With this it would be necessary, what we are doing is using the setVolcanInicio from Component2 and volcanInicio from Component1, taking advantage of the passage through props, using the parent (PageHome) as an "intermediary"
Given that a component is updated when its state or its props change, when the state of VolcanInicio changes, and this is defined in PageHome, every time something is entered in the input of Component2, the PageHome will be rendered, causing it to be displayed. the updated value in Component2.
In short, you pass the setVolcanInicio to the component that will make the change, this setter is a function, and the component that will show the data you pass through props VolcanInicio, this is the value that you will show.