How to select all options in react select? - reactjs

I am not able to implement select all option for react select.
Below is my code
Here I am using react-select with multi select option.
when I click on select all option it should select all options in the dropdown and save it in a state variable.
import React from "react";
import Select,{components} from 'react-select';
import '../App.css'
const options = [
{ value: '*', label: 'Select All' },
{ value: 'ocean', label: 'Ocean', color: '#00B8D9', isFixed: true },
{ value: 'blue', label: 'Blue', color: '#0052CC', isDisabled: true },
{ value: 'purple', label: 'Purple', color: '#5243AA' },
{ value: 'red', label: 'Red', color: '#FF5630', isFixed: true },
{ value: 'orange', label: 'Orange', color: '#FF8B00' },
{ value: 'yellow', label: 'Yellow', color: '#FFC400' },
{ value: 'green', label: 'Green', color: '#36B37E' },
{ value: 'forest', label: 'Forest', color: '#00875A' },
{ value: 'slate', label: 'Slate', color: '#253858' },
{ value: 'silver', label: 'Silver', color: '#666666' },
];
export default function ReactSelect() {
const [value,setValue]=React.useState([])
const handleChange = (val) => {
if(val && val.length && val[0].value==='*'){
let arr=options;
arr.splice(0,0);
setValue([...arr])
}
else{
setValue( [...val] );}
}
return (
<div id="select">
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen </p>
<Select
onChange={handleChange}
isMulti
name="colors"
options={options}
className="basic-multi-select"
classNamePrefix="select"
closeMenuOnSelect={false}
hideSelectedOptions={false}
components={{ ValueContainer }}
value={value}
/>
<button onClick={()=>console.log(value)}>CLick</button>
</div>
);
}
const ValueContainer = ({ children, ...props }) => {
let [values, input] = children;
if (Array.isArray(values)) {
const val = (i= Number) => values[i].props.children;
const { length } = values;
switch (length) {
case 1:
values = `${val(0)} `;
break;
default:
const otherCount = length - 1;
values = `${val(0)}+ ${otherCount} `;
break;
}
}
return (
<components.ValueContainer {...props}>
{values}
{input}
</components.ValueContainer>
);
};
I tried to implement with select all option but its not working. Is there any inbuilt facility for it or any other select library which has multi select option with select all facility.

Related

React - Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

After entering the color name in the input field, when I submit the form, an error occurs :
TypeError: Cannot read property 'toLowerCase' of undefined
(anonymous function)
C:/Users/HP/Documents/WDB/React/Practice/colors-app/src/NewPaletteForm.js:117
114 | //to check -> is 'palette name' unique
115 | ValidatorForm.addValidationRule("isPaletteNameUnique", value => {
116 | return palettes.every(
> 117 | ({ paletteName }) => paletteName.toLowerCase() !== value.toLowerCase()
118 | ^ );
119 | });
120 | })
App.js : (Class-based component)
class App extends Component {
constructor(props) {
super(props);
this.state = { palettes: seedColors };
this.findPalette = this.findPalette.bind(this);
this.savePalette = this.savePalette.bind(this);
}
savePalette(newPalette) {
this.setState({ palettes: [...this.state.palettes, newPalette] });
}
render() {
return (
<Switch>
<Route
exact
path='/palette/new'
render={(routeProps) =>
<NewPaletteForm
savePalette={this.savePalette}
palettes={this.state.palettes}
{...routeProps}
/>}
/>
NewPaletteForm.js : (Functional component and uses react hooks)
function NewPaletteForm(props) {
const classes = useStyles();
const [open, setOpen] = useState(false);
const [currentColor, setCurrentColor] = useState('teal');
const [colors, setColors] = useState([{ color: 'pink', name: 'pink' }]);
const [fields, setFields] = useState({
newColorName: '',
newPaletteName: ''
})
useEffect(() => {
ValidatorForm.addValidationRule('isColorNameUnique', (value) => {
return colors.every(
({ name }) => name.toLowerCase() !== value.toLowerCase()
);
});
ValidatorForm.addValidationRule('isColorUnique', (value) => {
return colors.every(
({ color }) => color !== currentColor
);
});
ValidatorForm.addValidationRule("isPaletteNameUnique", value => {
return props.palettes.every(
({ paletteName }) => paletteName.toLowerCase() !== value.toLowerCase()
);
});
})
function addNewColor() {
const newColor = {
color: currentColor,
name: fields.newColorName
}
setColors(oldColors => [...oldColors, newColor]);
setFields({ newColorName: '' });
};
function handleChange(evt) {
setFields({ ...fields, [evt.target.name]: evt.target.value });
}
function handleSubmit() {
let newName = fields.newPaletteName;
const newPalette = {
paletteName: newName,
id: newName.toLowerCase().replace(/ /g, '-'),
colors: colors
}
props.savePalette(newPalette);
props.history.push('/');
}
Validator form components for colors and palettes :
<ValidatorForm onSubmit={handleSubmit}>
<TextValidator
label='Palette Name'
value={fields.newPaletteName}
name='newPaletteName'
onChange={handleChange}
validators={['required', 'isPaletteNameUnique']}
errorMessages={['Enter Palette Name', 'Name already used']} />
<Button variant='contained' color='primary' type='submit'>
Save Palette
</Button>
</ValidatorForm>
<ValidatorForm onSubmit={addNewColor}>
<TextValidator
value={fields.newColorName}
name='newColorName'
onChange={handleChange}
validators={['required', 'isColorNameUnique', 'isColorUnique']}
errorMessages={['Enter a color name', 'Color name must be unique', 'Color already used!']}
/>
<Button
variant='contained'
type='submit'
color='primary'
style={{
backgroundColor: currentColor
}}
>
Add Color
</Button>
</ValidatorForm>
seedColors.js:
export default [
{
paletteName: "Material UI Colors",
id: "material-ui-colors",
emoji: "🎨",
colors: [
{ name: "red", color: "#F44336" },
{ name: "pink", color: "#E91E63" },
{ name: "purple", color: "#9C27B0" },
{ name: "deeppurple", color: "#673AB7" },
{ name: "indigo", color: "#3F51B5" },
{ name: "blue", color: "#2196F3" },
{ name: "lightblue", color: "#03A9F4" },
{ name: "cyan", color: "#00BCD4" },
{ name: "teal", color: "#009688" },
{ name: "green", color: "#4CAF50" },
{ name: "lightgreen", color: "#8BC34A" },
{ name: "lime", color: "#CDDC39" },
{ name: "yellow", color: "#FFEB3B" },
{ name: "amber", color: "#FFC107" },
{ name: "orange", color: "#FF9800" },
{ name: "deeporange", color: "#FF5722" },
{ name: "brown", color: "#795548" },
{ name: "grey", color: "#9E9E9E" },
{ name: "bluegrey", color: "#607D8B" }
]
},
{
paletteName: "Flat UI Colors v1",
id: "flat-ui-colors-v1",
emoji: "🤙",
colors: [
{ name: "Turquoise", color: "#1abc9c" },
{ name: "Emerald", color: "#2ecc71" },
{ name: "PeterRiver", color: "#3498db" },
{ name: "Amethyst", color: "#9b59b6" },
{ name: "WetAsphalt", color: "#34495e" },
{ name: "GreenSea", color: "#16a085" },
{ name: "Nephritis", color: "#27ae60" },
{ name: "BelizeHole", color: "#2980b9" },
{ name: "Wisteria", color: "#8e44ad" },
{ name: "MidnightBlue", color: "#2c3e50" },
{ name: "SunFlower", color: "#f1c40f" },
{ name: "Carrot", color: "#e67e22" },
{ name: "Alizarin", color: "#e74c3c" },
{ name: "Clouds", color: "#ecf0f1" },
{ name: "Concrete", color: "#95a5a6" },
{ name: "Orange", color: "#f39c12" },
{ name: "Pumpkin", color: "#d35400" },
{ name: "Pomegranate", color: "#c0392b" },
{ name: "Silver", color: "#bdc3c7" },
{ name: "Asbestos", color: "#7f8c8d" }
]
}
]
What you can do is check to see if the value exists before calling toLowerCase.
Try using ?., like this
Instead of using value.toLowerCase() use value?.toLowerCase().
That way if the value is undefined or null, it won't call toLowerCase()
If paletteName is the one failing you can use paletteName?.toLowerCase()
If you want to go completely safe you do
paletteName?.toLowerCase() !== value?.toLowerCase()

React select multi select one option not clearable

I am using react-select in my project. I have it for multiple select and it looks like this:
and it works fine. The problem is I would like to have one option already selected and it would be not clearable so it will not have "X" near it
I just need it for one option, all others have to be normally in the options and clearable.
How can I achieve that? Is it a special prop added to options or can I check them some way that if option name is commercial it will not have possibility to clear and would be selected on initial
react-select has a fixed options example on the docs but I found this solution is much cleaner. You can remove MultiValueRemove component (the delete button) based on the option value:
const MultiValueRemove = (props) => {
if (props.data.isFixed) {
return null;
}
return <components.MultiValueRemove {...props} />;
};
export default () => {
return (
<Select
isMulti
defaultValue={[colourOptions[0], colourOptions[1]]}
isClearable={false}
options={colourOptions}
components={{ MultiValueRemove }}
/>
);
};
The select above will remove the delete button of any option that has the isFixed property set to true (the first 2 options below).
export const colourOptions = [
{ value: 'ocean', label: 'Ocean', color: '#00B8D9', isFixed: true },
{ value: 'red', label: 'Red', color: '#FF5630', isFixed: true },
{ value: 'purple', label: 'Purple', color: '#5243AA' },
{ value: 'orange', label: 'Orange', color: '#FF8B00' },
{ value: 'yellow', label: 'Yellow', color: '#FFC400' },
{ value: 'green', label: 'Green', color: '#36B37E' },
{ value: 'forest', label: 'Forest', color: '#00875A' },
{ value: 'slate', label: 'Slate', color: '#253858' },
{ value: 'silver', label: 'Silver', color: '#666666' },
];
Live Demo
You can remove that by using isClearable props of react-select like below
Consider your options array have fixed boolean set to true
<Select
// other props
isClearable={options.some(v => !v.isFixed)}
/>
And you can change you multiValueRemove in styles const like this
const styles = {
// other styles here
multiValueRemove: (base, state) => {
return state.data.isFixed ? { ...base, display: 'none' } : base;
},
};
You can find more info in Fixed option section of https://react-select.com/home#fixed-options
Try this:
export const CreatingSelect: FC<CreatingSelectProps> = (props) => {
const { className, components, ...restProps } = props;
const selectClassName = cn('select', className);
const MultiValueRemove = (props: PropsWithChildren<any>) => {
return (
<div className={props.innerProps.className} onClick={props.innerProps.onClick}>
<SvgIcon name={iconNames.cross} />
</div>
);
};
return (
<SelectStyled
styles={customStyles}
className={selectClassName}
classNamePrefix='select'
components={{ ...components, MultiValueRemove }}
{...restProps}
/>
);
};

react-select change singleValue color based on options

I would like to modify the 'selected' singleValue color in my styles object based on the options that are provided.
const statusOptions = [
{ value: "NEW", label: i18n._(t`NEW`) },
{ value: "DNC", label: i18n._(t`DNC`) },
{ value: "WON", label: i18n._(t`WON`) },
{ value: "LOST", label: i18n._(t`LOST`) },
];
For example, if the option selected in "NEW", I want the font color to be red, if it's "WON", then green, and so on. I am having trouble putting an if statement into the styles object. I see that its simple to put a ternary statement in, but how to you add more "complex" logic?
const customStyles = {
...
singleValue: (provided) => ({
...provided,
color: 'red' <----- something like if('NEW') { color: 'green' } etc..
})
};
Use an style map object:
import React from 'react';
import Select from 'react-select';
const statusOptions = [
{ value: 'NEW', label: 'NEW' },
{ value: 'DNC', label: 'DNC' },
{ value: 'WON', label: 'WON' },
{ value: 'LOST', label: 'LOST' },
];
const styleMap = {
NEW: 'red',
DNC: 'blue',
};
const colourStyles = {
singleValue: (provided, { data }) => ({
...provided,
color: styleMap[data.value] ? styleMap[data.value] : 'defaultColor',
// specify a fallback color here for those values not accounted for in the styleMap
}),
};
export default function SelectColorThing() {
return (
<Select
options={statusOptions}
styles={colourStyles}
/>
);
}

How to count selected checkboxes in React functional component?

I am needing to add bit of text in the sidebar of the following code. In each section, I need to have a count of the number of checkboxes selected. Is it at all possible to do this in a functional component as I have? Any examples that I have found so far are only for class components. I would like to keep it as a functional component if possible.
I have the code below, but here is a working version too:
https://codesandbox.io/s/react-playground-forked-jgmof?file=/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { categoryData } from "./data";
const Menu = (props) => {
const [showPanel, togglePanel] = useState(false);
return (
<MenuWrapper>
<p>Showing 20 results</p>
<div className="button-wrapper">
<p>Filter By</p>
{categoryData.map((categorybutton, i) => (
<div key={i}>
<button key={i} onClick={() => togglePanel(!showPanel)}>
{categorybutton.category}
</button>
</div>
))}
<div>
{showPanel && (
<Sidebar>
{categoryData.map((categorysection, i) => (
<details className="dropdown-header">
<summary>{categorysection.category}</summary>
{categorysection.data.map((categorylabel, i) => (
<div key={i}>
<input
type="checkbox"
id="vehicle1"
name="vehicle1"
value="Bike"
/>
<label for="vehicle1">{categorylabel.label}</label>
</div>
))}
</details>
))}
</Sidebar>
)}
</div>
<p>Toggle</p>
<p>Clear all filters</p>
</div>
</MenuWrapper>
);
};
const MenuWrapper = styled.div`
width: 90vw;
display: flex;
justify-content: space-between;
.button-wrapper {
display: flex;
}
`;
const Sidebar = styled.div`
position: fixed;
width: 200px;
height: 100vh;
background: white;
top: 0;
left: 0;
z-index: 100000;
text-align: left;
.dropdown-header {
background: #f7f7f7;
margin: 20px;
}
`;
ReactDOM.render(<Menu />, document.getElementById("container"));
export const categoryData = [
{
category: "user",
data: [
{ checked: false, value: "Me", label: "Me" },
{ checked: false, value: "Kids", label: "Kids" },
{ checked: false, value: "Guestroom", label: "Guestroom" }
]
},
{
category: "comfort",
data: [
{ checked: false, value: "Ultra-Soft", label: "Ultra-Soft" },
{ checked: false, value: "Soft", label: "Soft" },
{ checked: false, value: "Medium", label: "Medium" },
{ checked: false, value: "Medium-Firm", label: "Medium-Firm" },
{ checked: false, value: "Firm", label: "Firm" },
{ checked: false, value: "Ultra-Firm", label: "Ultra-Firm" },
{ checked: false, value: "Unsure", label: "Unsure" }
]
},
{
category: "type",
data: [
{ checked: false, value: "Pillow Top", label: "Pillow Top" },
{ checked: false, value: "Open Coil", label: "Open Coil" },
{ checked: false, value: "Pocketed Coil", label: "Pocketed Coil" },
{ checked: false, value: "Quantum Coil", label: "Quantum Coil" },
{ checked: false, value: "Memory Foam", label: "Memory Foam" },
{ checked: false, value: "Latex", label: "Latex" },
{ checked: false, value: "Unsure", label: "Unsure" }
]
},
{
category: "budget",
data: [
{ checked: false, value: 500, label: "Under $500" },
{ checked: false, value: 1000, label: "$501 - $1000" },
{ checked: false, value: 1600, label: "1001 - $1600" },
{ checked: false, value: 2500, label: "$1601 - $2500" },
{ checked: false, value: 2501, label: "$2500 and up" },
{ checked: false, value: "Unsure", label: "Unsure" }
]
}
];
If I understand correctly, you wan't to show the total number of selected items on each category.
It would be easy if we'll create a new component for the section that will have it's own state tracking its selected items.
Let's call it CategorySection. It would then have a selected state that will be an array (empty by default) of its selected items. To update our selected state, we have to fireup a function everytime any of the checkbox is changed — if the checkbox is checked, we add the current item to our selected state otherwise it will be removed.
Then to display the total selected items, we can simply count the length of our selected state.
function CategorySection({ categorysection }) {
const [selected, setSelected] = useState([]);
function onChange(event, item) {
if (event.target.checked) {
setSelected([...selected, item]);
} else {
setSelected((prev) =>
prev.filter((currItem) => currItem.value !== item.value)
);
}
}
return (
<details className="dropdown-header">
<summary>
{categorysection.category}{" "}
{selected.length > 0 ? selected.length : null}
</summary>
{categorysection.data.map((categorylabel, i) => (
<div key={i}>
<input
type="checkbox"
id={categorylabel.value}
name="vehicle1"
value="Bike"
onChange={(event) => onChange(event, categorylabel)}
/>
<label for={categorylabel.value}>{categorylabel.label}</label>
</div>
))}
</details>
);
}
PS: You should have a unique id for every checkbox on your page.

Material ui v1 autocomplete - how to style it/ pass props to it?

Looking forward for any hint how to style new material ui v1 autocomplete or how to pass props to it.
Here's a codesandbox code (working example):
https://codesandbox.io/s/xrzq940854
In my particular case - I would like to style the label (which goes up after entering some value into input) and that horizontal line (underline under the input value).
Thank u for any help. (dropping code also in the snippet)
P.S. I got also a question how to pass props to the styles function. If anyone knows, please let me know :)
import React from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';
import match from 'autosuggest-highlight/match';
import parse from 'autosuggest-highlight/parse';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import { MenuItem } from 'material-ui/Menu';
import { withStyles } from 'material-ui/styles';
const suggestions = [
{ label: 'Afghanistan' },
{ label: 'Aland Islands' },
{ label: 'Albania' },
{ label: 'Algeria' },
{ label: 'American Samoa' },
{ label: 'Andorra' },
{ label: 'Angola' },
{ label: 'Anguilla' },
{ label: 'Antarctica' },
{ label: 'Antigua and Barbuda' },
{ label: 'Argentina' },
{ label: 'Armenia' },
{ label: 'Aruba' },
{ label: 'Australia' },
{ label: 'Austria' },
{ label: 'Azerbaijan' },
{ label: 'Bahamas' },
{ label: 'Bahrain' },
{ label: 'Bangladesh' },
{ label: 'Barbados' },
{ label: 'Belarus' },
{ label: 'Belgium' },
{ label: 'Belize' },
{ label: 'Benin' },
{ label: 'Bermuda' },
{ label: 'Bhutan' },
{ label: 'Bolivia, Plurinational State of' },
{ label: 'Bonaire, Sint Eustatius and Saba' },
{ label: 'Bosnia and Herzegovina' },
{ label: 'Botswana' },
{ label: 'Bouvet Island' },
{ label: 'Brazil' },
{ label: 'British Indian Ocean Territory' },
{ label: 'Brunei Darussalam' },
];
function renderInput(inputProps) {
const { classes, autoFocus, value, ref, ...other } = inputProps;
return (
<TextField
autoFocus={autoFocus}
className={classes.textField}
value={value}
inputRef={ref}
label="Country"
InputProps={{
classes: {
input: classes.input,
},
...other,
}}
/>
);
}
function renderSuggestion(suggestion, { query, isHighlighted }) {
const matches = match(suggestion.label, query);
const parts = parse(suggestion.label, matches);
return (
<MenuItem selected={isHighlighted} component="div">
<div>
{parts.map((part, index) => {
return part.highlight ? (
<span key={String(index)} style={{ fontWeight: 300 }}>
{part.text}
</span>
) : (
<strong key={String(index)} style={{ fontWeight: 500 }}>
{part.text}
</strong>
);
})}
</div>
</MenuItem>
);
}
function renderSuggestionsContainer(options) {
const { containerProps, children } = options;
return (
<Paper {...containerProps} square>
{children}
</Paper>
);
}
function getSuggestionValue(suggestion) {
return suggestion.label;
}
function getSuggestions(value) {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
let count = 0;
return inputLength === 0
? []
: suggestions.filter(suggestion => {
const keep =
count < 5 && suggestion.label.toLowerCase().slice(0, inputLength) === inputValue;
if (keep) {
count += 1;
}
return keep;
});
}
const styles = theme => ({
container: {
flexGrow: 1,
position: 'relative',
height: 200,
},
suggestionsContainerOpen: {
position: 'absolute',
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit * 3,
left: 0,
right: 0,
},
suggestion: {
display: 'block',
},
suggestionsList: {
margin: 0,
padding: 0,
listStyleType: 'none',
},
textField: {
width: '100%',
},
label: {
color: 'yellow',
}
});
class IntegrationAutosuggest extends React.Component {
state = {
value: '',
suggestions: [],
};
handleSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value),
});
};
handleSuggestionsClearRequested = () => {
this.setState({
suggestions: [],
});
};
handleChange = (event, { newValue }) => {
this.setState({
value: newValue,
});
};
render() {
const { classes } = this.props;
return (
<Autosuggest
theme={{
container: classes.container,
suggestionsContainerOpen: classes.suggestionsContainerOpen,
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderInputComponent={renderInput}
suggestions={this.state.suggestions}
onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
renderSuggestionsContainer={renderSuggestionsContainer}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={{
autoFocus: true,
classes,
placeholder: 'Search a country (start with a)',
value: this.state.value,
onChange: this.handleChange,
}}
/>
);
}
}
IntegrationAutosuggest.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(IntegrationAutosuggest);
Material-UI v1 uses React-autosuggest module.
Check the below link
https://github.com/moroshko/react-autosuggest/blob/master/src/Autosuggest.js

Resources