If I have variable as such:
const [APIKey, setAPIKey] = useState([])
Can I group these into 1 variable and pass it along as a prop?
const passAPI = {APIKey, setAPIKey}
Here is how I'm attempting to pass it:
const Home = () => {
const [APIKey, setAPIKey] = useState([])
const [Symbols, setSymbols] = useState([])
const [Endpoint, setEndpoint] = useState([])
const [Base, setBase] = useState([])
const passAPI = {APIKey, setAPIKey}
const passSymbols = {Symbols, setSymbols}
const passEndpoint = {Endpoint, setEndpoint}
const passBase = {Base, setBase}
return (
<Grid container spacing='8' className='HomeWrapper'>
<Grid item sx={{ display: { xs: 'none', sm: 'flex' }, width: '50%' }} className='x1'>
<Paper elevation='6' className='HomePaper' sx={{ width: '100%'}}>
<TopLeft passAPI={passAPI} passSymbols={passSymbols} passEndpoint={passEndpoint} passBase={passBase}/>
</Paper>
</Grid>
...
And here is an example of how I was trying to use it:
const TopRight = ({passAPI, passSymbols, passEndpoint, passCurrency}) => {
return (
<Box className='TopRightWrapper' sx={{ display: 'flex', flexDirection: 'column' }} pl={2} pt={1} pb={1}>
<FormControl onSubmit={passAPI}>
<Box>
<InputLabel htmlFor="my-input">API Key</InputLabel>
<Input id="my-input" aria-describedby="my-helper-text" />
<button type='submit'>click</button>
</Box>
</FormControl>
I would want to use the setAPIKey function that is found in the passAPI variable. How do I go about this?
As I can see passAPI in your case is an object. So to get setState from passAPI you should use "passAPI.setAPIKey" in onSubmit. So it should be like that:
<FormControl onSubmit={passAPI.setAPIKey}>
<Box>
<InputLabel htmlFor="my-input">API Key</InputLabel>
<Input id="my-input" aria-describedby="my-helper-text" />
<button type='submit'>click</button>
</Box>
</FormControl>
Also FormControl API does not have onSubmit event, you should use "form" tag instead. Through form onSumbit event argument you would be able to access "target" property which would have form elements inside, and then you will access value of that input element. Something like that
<form
onSubmit={(e) => {
e.preventDefault();
console.log("e", e.target[0].value);
passAPI.setAPIKey(e.target[0].value)
}}
>
Let me know if it helps.