Is there a way to use react multiple select with this - javascript

I formerly have a checkbox like this
renderCategoriesMD() {
const { classes, categoriesArray } = this.props;
const { checkedCategories, reset } = this.state;
if (categoriesArray && categoriesArray.length > 0) {
return categoriesArray.map((cat, index) => {
return (
<div>
<FormControlLabel
key={index}
control={
<Checkbox
tabIndex={-1}
onClick={() => this.handleToggleCats(index)}
checked={checkedCategories.indexOf(index) !== -1}
checkedIcon={<Check className={classes.checkedIcon} />}
icon={<Check className={classes.uncheckedIcon} />}
classes={{
checked: classes.checked,
root: classes.checkRoot,
}}
/>
}
classes={{ label: classes.label }}
label={
<Typography style={{ fontSize: 13 }}>
{cat.name || ""}
</Typography>
}
/>
{!reset && (
<div style={{ marginLeft: 10 }}>
{this.renderUnderSubCategoriesMD(cat)}
</div>
)}
</div>
);
});
}
return null;
}
What this does is populate options of checkboxes like the image below.
what i want to achieve now is to have react-select of multiple options so instead of checkboxes i can select the options from react select.
<Select
value={this.state.value}
name="filter__statistics"
options={options}
onChange={this.handleChange}
multi={true}
/>

I recommend you to use the npm packages, it is very easy to use and implement. npm react-select
There is an example
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
class App extends React.Component {
state = {
selectedOption: null,
};
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}

Related

Attempting to show array element of react select in list item of another class

I am new to react so I might be missing something
I am using react-select to store multiple elements and am using the map function to display elements which is working fine. But when I am using the same element in another class to display in a list element it shows a blank.
Here is the code where I am displaying the multiple options.
const Departments = [
{ label: "OneIT", value: "OneIT" },
{ label: "HR", value: "HR" },
{ label: "Vigilance", value: "Vigilance" },
{ label: "Ethics", value: "Ethics" },
{ label: "Corporate Services", value: "Corporate Services" },
{ label: "Legal", value: "Legal" },
{ label: "Sports", value: "Sports" },
{ label: "TQM", value: "TQM" },
{ label: "Iron Making", value: "Iron Making" },
{ label: "TMH", value: "TMH" },
];
class MultiSelect2 extends Component {
state = {
selectedOptions: [],
};
handleChangeField = (selectedOptions) => {
this.setState({ selectedOptions });
};
render() {
const { selectedOption } = this.state;
return (
<div className="container">
<div className="row">
<div className="col-md-2"></div>
<div className="col-md-8">
<span>Select Department</span>
<Select
value={selectedOption}
options={Departments}
onChange={this.handleChangeField}
isMulti
/>
{this.state.selectedOptions.map((o) => (
<p>{o.value}</p>
))}
</div>
<div className="col-md-4"></div>
</div>
</div>
);
}
}
I am trying to display this in another class in the list item but it is not showing.
export class Confirm extends Component {
state = {
selectedOptions: [],
};
render() {
const {
values: { selectedOptions },
} = this.props;
return (
<List>
<ListItemText primary="Departments" secondary={selectedOptions} />
</List>
);
}
}
I know I might be missing something very basic but please help
#Kubwimana Adrien
Here is the rest of the code:
export class Confirm extends Component {
state = {
rows: [],
idx: [],
selectedOptions: []
};
continue = e => {
e.preventDefault();
//Process Form//
this.props.nextStep();
};
back = e => {
e.preventDefault();
this.props.prevStep();
};
render() {
const {
values: {
Title,
Details,
What,
Why,
How,
Status,
Cost,
Benefits,
Kpi_Before,
Kpi_After,
Time,
dateTime,
Base_Before,
Target_Before,
UOM_Before,
idx,
selectedOptions
}
} = this.props;
return (
<MuiThemeProvider theme={theme}>
<React.Fragment>
<div className={useStyles.root}>
<AppBar position="static">
<Toolbar>
<Typography
gutterBottom
align="center"
style={{ width: "100%", alignItems: "center" }}
>
Confirm Information
</Typography>
</Toolbar>
</AppBar>
</div>
<br />
<h3>Are you sure to continue and confirm your information?</h3>
<List>
<ListItemText primary="Departments" secondary={selectedOptions} />
<ListItemText primary="Title" secondary={Title} />
<ListItemText primary="Kpi_Before" secondary={Kpi_Before} />
</List>
<p> {this.state.selectedOptions.map(o => (
<p>{o.value}</p>
))}</p>
<br />
<Button
variant="contained"
color="primary"
style={styles.button}
onClick={this.continue}
>
Confirm & Continue
</Button>
<Button
variant="contained"
color="default"
style={styles.button}
onClick={this.back}
>
Back
</Button>
</React.Fragment>
</MuiThemeProvider>
);
}
}
const theme = createMuiTheme({
palette: {
primary: blue,
secondary: purple
},
status: {
danger: "orange"
}
});
const styles = {
button: {
margin: 15
}
};
export default Confirm;

useState in react hooks converting to functional component

I am trying to convert the setState into useState.
so I followed the below article and converted partially
https://medium.com/javascript-in-plain-english/state-management-with-react-hooks-no-redux-or-context-api-8b3035ceecf8- but not sure how to convert the props
but its not rendering the values.
so I debugged and put console inside useEffect.
I am getting undefind at this line, am I using useState wrongly
useEffect(() => {
console.log("useEffect setspHeight--->", setspHeight);
can you let me know how to fix it and do I need to make any other changes for react hooks
class component code
import React, { Fragment, useState, Component } from 'react';
import styles from './styles';
import { withStyles } from '#material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '#material-ui/icons/ExpandMore';
import IconButton from '#material-ui/core/IconButton';
import Button from '#material-ui/core/Button';
import ExpansionPanel from '#material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '#material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '#material-ui/core/ExpansionPanelDetails';
import Typography from '#material-ui/core/Typography';
import Drawer from '#material-ui/core/Drawer';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
import Checkbox from '#material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
import dataStyles from '../../../../styles.css';
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
const radioValues = [
{
label: 'Select All Providers for This Category',
value: 'PRO',
},
];
class SportsExpansion extends Component {
state = {
value: 0,
spHeight: [],
spLength: '',
};
componentDidMount() {
this.setState({ spHeight: this.props.spHeight });
if (
this.props.spHeight.filter(
check => check.spWeight === 'One'
).length > 0
) {
this.setState({ value: 0 });
} else if (
this.props.spHeight.filter(
check => check.spWeight === 'Two'
).length > 0
) {
this.setState({ value: 1 });
}
}
handleChange = (event, value) => {
console.log('handleChange -value', value);
this.setState({ value });
};
handleSportsRadioValueChange = (category, value) => {
console.log('handleSportsRadioValueChange -category', category);
console.log('handleSportsRadioValueChange -value', value);
this.setState({ spLength: value });
};
render() {
const { classes, data } = this.props;
let udVal = '';
let starVal = '';
udVal = data.udVals ? data.udVals[0].number : '';
starVal = data.starVals ? data.starVals[0].number : '';
const { canEdit, value } = this.state;
const { spHeight } = this.state;
return (
<div>
<AppBar
className={classes.benchmarkTabHeader}
position="static"
color="default"
>
<Tabs
onChange={this.handleChange}
variant="scrollable"
scrollButtons="on"
indicatorColor="primary"
textColor="primary"
style={{ display: 'block' }}
classes={{
indicator: classes.tabsIndicator,
scrollButtons: classes.MuiPrivateTabScrollButton,
}}
>
<Tab
style={{
display:
this.state.spHeight.filter(
check =>
check.spWeight === 'One'
).length === 0
? 'none'
: '',
color: value == 0 ? '#1976D2' : '#66696C',
}}
label={`Groups (${
this.state.spHeight.filter(
check =>
check.spWeight === 'One'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
<Tab
style={{
display:
this.state.spHeight.filter(
check =>
check.spWeight ===
'Two'
).length === 0
? 'none'
: '',
color: value == 1 ? '#1976D2' : '#66696C',
}}
label={`Two (${
this.state.spHeight.filter(
check =>
check.spWeight ===
'Two'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div>
{' '}
<FormControl
component="fieldset"
className={classes.formControl}
>
<FormLabel component="legend" />
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={this.state.spLength}
onChange={e => {
this.setState({
spLength: e.target.value,
});
}}
>
{this.state.spHeight
.filter(
check =>
check.spWeight ===
'One'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.value}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
)}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
<Drawer
style={{ width: 500 }}
anchor="right"
open={this.state.right}
>
<div tabIndex={0} role="button"></div>
</Drawer>
</div>
</TabContainer>
)}
{value === 1 && (
<TabContainer>
<div>
<div>
<FormControl
component="fieldset"
className={classes.formControl}
>
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={this.state.spLength}
onChange={e => {
this.setState({
spLength:
e.target.value,
});
}}
>
{this.state.spHeight
.filter(
check =>
check.spWeight ===
'Two'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.label}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
</div>
</div>
</TabContainer>
)}
</div>
);
}
}
export default withStyles(styles)(SportsExpansion);
////////////////////////////////////////////////
functional component code
import React, { Fragment, useState, useEffect, Component } from 'react';
import styles from './styles';
import { withStyles } from '#material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '#material-ui/icons/ExpandMore';
import IconButton from '#material-ui/core/IconButton';
import Button from '#material-ui/core/Button';
import ExpansionPanel from '#material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '#material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '#material-ui/core/ExpansionPanelDetails';
import Typography from '#material-ui/core/Typography';
import Drawer from '#material-ui/core/Drawer';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
import Checkbox from '#material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
import dataStyles from '../../../../styles.css';
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
const radioValues = [
{
label: 'Select All Providers for This Category',
value: 'PRO',
},
];
//class SportsExpansion extends Component {
const SportsExpansion = (props) => {
const [value, setValue] = useState(0);
const [spHeight, setspHeight] = useState([]);
const [spLength, setspLength] = useState('');
// const { classes, data } = this.props;
const { classes, data } = props;
let udVal = '';
let starVal = '';
udVal = data.udVals ? data.udVals[0].number : '';
starVal = data.starVals ? data.starVals[0].number : '';
// const { canEdit, value } = this.state;
// const { spHeight } = this.state;
useEffect(() => {
// code to run on component mount
console.log("useEffect setspHeight--->", setspHeight);
//this.setState({ spHeight: this.props.spHeight });
setspHeight(spHeight);
if (
spHeight.filter(
check => check.spWeight === 'One'
).length > 0
) {
useState({ value: 0 });
} else if (
spHeight.filter(
check => check.spWeight === 'Two'
).length > 0
) {
useState({ value: 1 });
}
}, [])
//handleChange = (event, value) => {
const handleChange = (event, value) => {
console.log('handleChange -value', value);
useState({ value });
};
// handleSportsRadioValueChange = (category, value) => {
const handleSportsRadioValueChange = (category, value) => {
console.log('handleSportsRadioValueChange -category', category);
console.log('handleSportsRadioValueChange -value', value);
useState({ spLength: value });
};
return (
<div>
<AppBar
className={classes.benchmarkTabHeader}
position="static"
color="default"
>
<Tabs
onChange={this.handleChange}
variant="scrollable"
scrollButtons="on"
indicatorColor="primary"
textColor="primary"
style={{ display: 'block' }}
classes={{
indicator: classes.tabsIndicator,
scrollButtons: classes.MuiPrivateTabScrollButton,
}}
>
<Tab
style={{
display:
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight === 'One'
).length === 0
? 'none'
: '',
color: value == 0 ? '#1976D2' : '#66696C',
}}
label={`Groups (${
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight === 'One'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
<Tab
style={{
display:
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight ===
'Two'
).length === 0
? 'none'
: '',
color: value == 1 ? '#1976D2' : '#66696C',
}}
label={`Two (${
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight ===
'Two'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div>
{' '}
<FormControl
component="fieldset"
className={classes.formControl}
>
<FormLabel component="legend" />
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={//this.state.spLength
spLength}
onChange={e => {
useState({
spLength: e.target.value,
});
}}
>
{//this.state.spHeight
spHeight
.filter(
check =>
check.spWeight ===
'One'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.value}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
)}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
{/*<Drawer
style={{ width: 500 }}
anchor="right"
open={
//this.state.right
right}
>
<div tabIndex={0} role="button"></div>
</Drawer>*/}
</div>
</TabContainer>
)}
{value === 1 && (
<TabContainer>
<div>
<div>
<FormControl
component="fieldset"
className={classes.formControl}
>
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={//this.state.spLength
spLength}
onChange={e => {
useState({
spLength:
e.target.value,
});
}}
>
{//this.state.spHeight
spHeight
.filter(
check =>
check.spWeight ===
'Two'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.label}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
</div>
</div>
</TabContainer>
)}
</div>
);
}
export default withStyles(styles)(SportsExpansion);
You have to replace where you call useState({ value: 1 }); to setValue(value)
You are using useState wrong. useState replaces the state object. The first value in the array is the value you can call in your component. The second value in the array replaces this.setState and sets the value of the state instance. So to use the useState hook if you had the following:
const [value, setValue] = useState(0);
you would use value in your component to reference this state instance. And you would use setValue to set the value of this state instance. So to set value to 2 you would do setValue(2).

react-form-validator not registering children components?

I am using 'react-form-validator-core' package and trying to create a custom form validator that implements 'mui-downshift', a Material UI implementation of PayPal's downshift. This question is mostly about 'react-form-validator-core' package itself. The problem is that the form itself does not register the validator component I've created. Here is my full code of the custom component and the form itself. I've exhausted my debugging skills, but what I noticed is that there's something wrong with the this.context in the form...
Validator component:
import React from 'react';
import PropTypes from 'prop-types';
import MuiDownshift from 'mui-downshift';
import { ValidatorComponent } from 'react-form-validator-core';
class AutocompleteValidator extends ValidatorComponent {
constructor(props) {
debugger;
super(props);
this.originalItems = props.items.map(({key, name}) => ({ text: name, value: key }));
this.handleStateChange = this.handleStateChange.bind(this);
this.errorText = this.errorText.bind(this);
}
componentWillMount() {
if (!this.filteredItems) {
this.setState({filteredItems: this.originalItems});
}
if (!!this.props.value) {
const selectedItem = this.originalItems.filter(
item => item.value.toLowerCase().includes(this.props.value.toLowerCase())
)[0];
this.setState({ selectedItem })
} else {
this.setState({ selectedItem: null})
}
}
componentWillReceiveProps(nextProps) {
// If no filteredItems in sate, get the whole list:
if (!nextProps.value) {
this.setState({ isValid: false })
}
}
handleStateChange(changes) {
// If searching
if (changes.hasOwnProperty('inputValue')) {
const filteredItems = this.originalItems.filter(
item => item.text.toLowerCase().includes(changes.inputValue.toLowerCase())
);
this.setState({ filteredItems })
}
// If something is selected
if (changes.hasOwnProperty('selectedItem')) {
!!changes.selectedItem ? this.setState({isValid: true}) : this.setState({isValid: false})
// If we get undefined, change to '' as a fallback to default state
changes.selectedItem = changes.selectedItem ? changes.selectedItem : '';
this.props.onStateChange(changes);
}
}
errorText() {
const { isValid } = this.state;
if (isValid) {
return null;
}
return (
<div style={{ color: 'red' }}>
{this.getErrorMessage()}
</div>
);
}
render() {
return (
<div>
<MuiDownshift
{...this.props}
items={this.state.filteredItems}
onStateChange={this.handleStateChange}
ref={(r) => { this.input = r; }}
defaultSelectedItem={this.state.selectedItem}
/>
{this.errorText()}
</div>
);
}
}
AutocompleteValidator.childContextTypes = {
form: PropTypes.object
};
export default AutocompleteValidator;
A component where it's used:
render() {
return (
<ValidatorForm
ref='form'
onSubmit={() => {
this.context.router.history.push(this.props.config.urls['step5']);
}}
onError={errors => console.log(errors)}
>
<Row>
<Col md={12}>
<AutocompleteValidator
validators={['required']}
errorMessages={['Cette information doit être renseignée']}
isRequired={true}
name='bankId'
items={this.props.config.list.bank}
onStateChange={(changes) => {
this.props.loansUpdate('bankId', changes.selectedItem.value);
}}
value={!!this.props.loans.bankId ? this.props.loans.bankId : false}
/>
</Col>
</Row>
<Row>
<Col md={12} style={{ marginTop: '15px' }}>
<Checkbox
label={<Translate value='step4.insuranceProvidedByBank' />}
labelStyle={{ 'top': '0px' }}
name='insuranceProvidedByBank'
value={this.props.loans.insuranceProvidedByBank}
checked={this.props.loans.insuranceProvidedByBank}
onCheck={(event, value) => {
this.props.loansUpdate('insuranceProvidedByBank', value);
}}
/>
</Col>
</Row>
<Row>
<Col sm={6} md={5}>
<Button
fullWidth
style={{ marginTop: '50px', marginBottom: '20px' }}
type='submit'
icon={<i className='fa fa-angle-right' style={{ marginLeft: '10px', display: 'inline-block' }} />}
><Translate value='iContinue' /></Button>
</Col>
</Row>
</ValidatorForm >
)
};
};
you get this problem because you override default componentWillMount and componentWillReceiveProps methods from ValidatorComponent. So, to solve this case you should do something like this
componentWillMount() {
// should call parent method before
super.componentWillMount();
// your code
}

Validation in React To-do app

I have simple to-do app and trying to do validation for adding new task mainly I want to prevent user to add a blank task to the list - my React skills are very poor so please forgive this silly question.
if you have any idea how to solve my problem please let me know thanks!
import React, { Component } from 'react';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
import TextField from 'material-ui/TextField';
import List from './List';
import '../App.css';
class App extends Component {
state = {
query: '',
inputValue: '',
todos: [
{ value: 'Naumiej się Reacta', done: false },
{ value: 'Pucuj trzewiki ', done: true },
],
direction: 'row',
justify: 'left',
alignItems: 'left',
}
handleChange = (evt) => {
this.setState({ inputValue: evt.target.value });
}
removeMe = (index) => {
this.setState({
todos: this.state.todos.filter((_, i) => i !== index)
})
}
searchChanged = (evt) => {
this.setState({ query: evt.target.value })
}
handleSubmit = (evt) => {
if (evt.keyCode === 13) {
const newTodo = {
value: this.state.inputValue,
done: false
};
const todos = this.state.todos.concat(newTodo);
this.setState({ todos: todos, inputValue: '' })
}
}
render() {
return (
<Grid item xs={12} style={{ padding: 30, display: 'flex' }}>
<div className="App">
<Typography type="body1'" color="inherit" text-align='left'>
<AppBar position="static" color="default" style={{ flexDirection: 'center' }}>
<Toolbar>
<TextField
style={{ float: 'left', paddingRight: 40, }}
placeholder="Add Task ..."
onChange={this.handleChange}
inputValue={this.state.inputValue}
onKeyDown={this.handleSubmit}
>
</TextField>
<TextField ype="text" placeholder="Search..." onChange={this.searchChanged} />
</Toolbar>
</AppBar>
</Typography>
<Paper>
<List style={{ marginTop: 90 }}
removeMe={this.removeMe}
todos={this.state.todos}
query={this.state.query}
/>
</Paper>
</div>
</Grid>
);
}
}
export default App;
I think you did correctly. Just return before submit or check for value with enter key.
handleSubmit = (evt) => {
if (evt.keyCode === 13 && this.state.inputValue) {
const newTodo = {
value: this.state.inputValue,
done: false
};
const todos = this.state.todos.concat(newTodo);
this.setState({todos: todos, inputValue: ''})
}
}

React Select - setState of prop

I am trying to set the state of my brandSelect prop in ReactJS using React Select however I am confused to how this can be done?
Here is my current code:
class VehicleSelect extends React.Component {
constructor(props) {
super(props);
this.state = { brandSelect: ""};
}
render() {
var options = [
{ value: 'Volkswagen', label: 'Volkswagen' },
{ value: 'Seat', label: 'Seat' }
];
return (
<Select
name="form-field-name"
value={this.state.brandSelect}
options={options}
placeholder="Select a brand"
searchable={false}
onChange={}
/>
)
}
};
When the option is selected I want the state to be set as the option chosen.
Does anybody know how this is done with React Select as the documentation doesn't really cover this? So far I have tried making a function with a set state attached to the onChange prop however this didn't work.
In react 16.8+ the implementation should look like this using React hooks:
Hooks are a new addition in React 16.8
function VehicleSelect() {
const options = [
{ value: 'volkswagen', label: 'Volkswagen' },
{ value: 'seat', label: 'Seat' }
];
const [selectedOption, setSelectedOption] = useState({ value: 'volkswagen', label: 'Volkswagen' });
const [handleChange] = useState(() => {
return () => {
setSelectedOption(selectedOption);
};
});
return (
<div className="App">
<Select
name="form-field-name"
placeholder="Select a brand"
searchable={false}
value={selectedOption}
onChange={handleChange}
options={options}
/>
</div>
);
}
You can try do add _onChange handler to your component, that will handle changes form <Select /> component.
class VehicleSelect extends React.Component {
constructor(props) {
super(props);
this.state = { brandSelect: ""};
}
_onChange(value) {
//console.log(value) - just to see what we recive from <Select />
this.setState({brandSelect: value});
}
render() {
var options = [
{ value: 'Volkswagen', label: 'Volkswagen' },
{ value: 'Seat', label: 'Seat' }
];
return (
<Select
name="form-field-name"
value={this.state.brandSelect}
options={options}
placeholder="Select a brand"
searchable={false}
onChange={this._onChange.bind(this)}
/>
)
}
};
Try this:
class VehicleSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
brandSelect: ""
};
}
onSelectChanged(value) {
this.setState({
brandSelect: value
});
}
render() {
var options = [{
value: 'Volkswagen',
label: 'Volkswagen'
}, {
value: 'Seat',
label: 'Seat'
}];
<Select
name="form-field-name"
value={this.state.brandSelect}
options={options}
placeholder="Select a brand"
searchable={false}
onChange={this.onSelectChanged.bind(this)}
/>
You need an onChange event handler. Pass in an argument to the event handler function which in this case will be the selected value of the Select input and then Set the State of the brandSelect with the selected value.
I used this in my code to work with Selector:
class VehicleSelect extends React.Component {
constructor(props) {
super(props);
this.state = { brandSelect: ""};
}
onChange(event) {
this.setState({brandSelect: event.target.value}); // important
}
render() {
var options = [
{ value: 'Volkswagen', label: 'Volkswagen' },
{ value: 'Seat', label: 'Seat' }
];
return (
<Select
name="form-field-name"
value={this.state.brandSelect}
options={options}
placeholder="Select a brand"
searchable={false}
onChange={this.onChange.bind(this)}
/>
)
}
};
const Layout = (props: any) => {
//Row First
const [rows, setRow] = useState({
rowFirst: "",
columnFirst: "",
columnSecond: 0
});
const handleChangeRowFirst = (e: { target: { name: any; value: any; }; }) => {
setRow({ ...rows, [e.target.name]: e.target.value });
console.log("row", rows);
props.dispatch({
type: "setRow",
payload: rows
});
};
const onSubmitForm = (e: any) => {
e.preventDefault();
if (!rows.rowFirst) {
alert("rowFirst is empty.")
}
else if (!rows.columnFirst) {
alert("columnFirst or rowFirst is empty.")
}
else if (!rows.columnSecond) {
alert("columnSecond is empty.")
}
}
return (
<>
<Grid container className="containerMatrix">
<form onSubmit={onSubmitForm} className="formMatrix">
<Grid item xs={6} md={5}>
<Box id="test" className="martixNum">
<Typography variant="h5" gutterBottom className="nameColMatrix">
Enter Numbers First Matrix
</Typography>
<Box className="martixFirst">
<TextField
type="number"
InputProps={{
inputProps: {
max: 99, min: 0
}
}}
label="Row" onChange={handleChangeRowFirst} name="rowFirst" id="num1" value={rows.rowFirst}
/>
<TextField
type="number"
InputProps={{
inputProps: {
max: 99, min: 0
}
}}
label="Column" onChange={handleChangeRowFirst} name="columnFirst" id="num2" value={rows.columnFirst}
/>
</Box>
</Box>
</Grid>
<Grid item xs={6} md={5}>
<Box id="test" className="martixNum">
<Typography variant="h5" gutterBottom className="nameColMatrix">
Enter Numbers Second Matrix
</Typography>
<Box className="martixFirst">
<TextField
type="number"
InputProps={{
inputProps: {
max: 99, min: 0
}
}}
label="Row" onChange={handleChangeRowFirst} name="columnFirst" id="num3" value={rows.columnFirst}
/>
<TextField
type="number"
InputProps={{
inputProps: {
max: 99, min: 0
}
}}
label="Column" onChange={handleChangeRowFirst} name="columnSecond" id="num4"
/>
</Box>
</Box>
</Grid>
<Grid item xs={6} md={5}>
<Box>
<Button variant="contained" color="primary" type="submit">
Primary
</Button>
</Box>
</Grid>
</form>
</Grid>
</>
)
}

Categories