code:
import React, { useState } from 'react';
const lookup = {
"num": [
{ id: '1', text: '1' },
{ id: '2', text: '2' },
{ id: '3', text: '3' },
{ id: '4', text: '4' },
{ id: '5', text: '5' }
],
"en": [
{ id: 'a', text: 'a' },
{ id: 'b', text: 'b' },
{ id: 'c', text: 'c' },
{ id: 'd', text: 'd' },
{ id: 'e', text: 'e' }
]
}
const App = ({}) => {
this.setState()
const [ data ] = useState('num');
const { data } = this.state;
const options = lookup[data];
return (
<div>
<select onChange = {({ target: { value } }) => {this.setState({ data: value })}}>
<option value="num">Integers</option>
<option value="en">Alphabets</option>
</select>
<hr />
<select>
{options.map(a => <option key={a.id} value={a.id}>{a.text}</option>)}
</select>
</div>
);
}
export default App;
error:
Failed to compile
./src/App.js
Line 30:11: Parsing error: Identifier 'data' has already been declared
28 | const [ data ] = useState('num');
29 |
> 30 | const { data } = this.state;
| ^
31 |
32 |
33 | const options = lookup[data];
An error occurred while changing from a class component to a function component. I'm not good at english i want cascading select option A compilation error occurs when running I'm still a beginner, so I don't know what's wrong How can I solve it I want a function component, not a class component
Since you are converting to a functional component, there's no need to use this.state
.
The useState hook returns a tuple where the first element is the state and the 2nd one is the setter for that state.
So here in your case you can use like this:
const [ data, setData ] = useState('num');
Now call the setData from the onChange callback.
<select onChange = {({ target: { value } }) => {setData(value);}}>
This will update the data
state and will rerender the component.