For example, if I have the functional component Dropdown that receives data from an api to populate a dropdown selection, and uses the following hook to update the state of the value selected
const [value, setValue] = React.useState();
How might I then access/read the value (in this case an array of numbers) outside of the Dropdown component?
For better context I will include firstly where the Dropdown component is used:
import React from 'react';
import Dropdown from '../Components/Dropdown.js'
import GraphTypeDropdown from '../Components/GraphTypeDropdown.js'
function CreateGraph() {
//function receiving and returning data (array of data points and their heading) from api
async function getData() {
const response = await fetch('/dropdowndata');
const receivedData = await response.json();
return receivedData;
}
//assigning data to myData variable
const myData = getData();
//myData is passed to Dropdown components as a prop to allow selection of data columns
//GraphTypeDropdown allows selection of the graph "type"
return (
<div>
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<GraphTypeDropdown />
</div>
)
}
export default CreateGraph;
And also the full code of the dropdown functional component
import React from 'react';
import './Dropdown.css';
function Dropdown(props) {
const [columns, setColumns] = React.useState([]);
const [value, setValue] = React.useState();
//maps the prop myData to be the label and value of the dropdown list
React.useEffect(() => {
async function getColumns() {
props.myData.then(function(result) {
setColumns(result.map(({ heading, values }) => ({ label: heading, value: values })));
});
}
getColumns();
}, [props.myData]);
//creates a dropdown where value (array of data points) can be selected with label (column headings)
//value selected is then saved in the state of the dropdown
return (
<select className='DropDown'
value={value}
onChange={(e) => setValue(e.currentTarget.value)}
>
{columns.map(({ label, heading, value }) => (
<option className='DropDown'
key={heading}
value={value}
>
{label}
</option>
))}
</select>
);
}
export default Dropdown;
How will I be able to use/access the arrays assigned to value in the five Dropdown components?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…