Ad
Preselect An Element From The List Of Elements In Material-UI Select Component
I want to preselect the element with the id 3 of my list. If I don't provide a preselected element it should automatically show the disabled item. Currently, the select box only shows Choose your option and if I try to pass down alreadySelected it's not working and I can't change my option later.
My app component:
import React from "react";
import ReactDOM from "react-dom";
import CustomSelect from "./components/Select";
function App() {
const [selectElement, setSelectElement] = React.useState(0);
// This element should be passed somehow down to the select component
const alreadySelected = 3;
return (
<div className="App">
<CustomSelect
selectElement={selectElement}
setSelectElement={setSelectElement}
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
My select component:
import React from "react";
import * as PropTypes from "prop-types";
import { FormControl, InputLabel, MenuItem, Select } from "@material-ui/core";
function CustomSelect(props) {
const { selectElement, setSelectElement } = props;
const list = [
{
id: 1,
name: "test 1"
},
{
id: 2,
name: "test 2"
},
{
id: 3,
name: "test 3"
}
];
function handleChange(event) {
setSelectElement(event.target.value);
}
return (
<FormControl fullWidth>
<InputLabel htmlFor="qualification-type">Select box</InputLabel>
<Select value={selectElement} onChange={handleChange}>
<MenuItem disabled value={0}>
<em>Choose your option</em>
</MenuItem>
{list.map(item => (
<MenuItem key={`type-${item.id}`} value={item.id}>
{item.name}
</MenuItem>
))}
</Select>
</FormControl>
);
}
CustomSelect.propTypes = {
selectElement: PropTypes.number.isRequired,
SetSelectElement: PropTypes.func.isRequired
};
export default CustomSelect;
Ad
Answer
useState
hook accepts default value as param. You have give 0 as default. Instead:
Use your state default value as 3:
const [selectElement, setSelectElement] = React.useState(3);
Yiu can even dynamically derive and pass as default value to state. Let me know.
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad