Semantic react ui dropdown multiple selection: option to Select All - reactjs

I am developing a react application based on hooks and for multi select dropdown am using react semantic ui Dropdown. But there is no option to Select All items. How to acheieve this? On click of Select All all the items should be selected and not be shown in the dropdown:-
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "select all", text: "Select All", value: "Select All" },
{ key: "angular", text: "Angular", value: "angular" },
{ key: "css", text: "CSS", value: "css" },
{ key: "design", text: "Graphic Design", value: "design" },
{ key: "ember", text: "Ember", value: "ember" },
{ key: "html", text: "HTML", value: "html" },
{ key: "ia", text: "Information Architecture", value: "ia" },
{ key: "ux", text: "User Experience", value: "ux" }
];
const DropdownExampleMultipleSelection = () => {
const [selectedItems, setSelectedItems] = useState([]);
const onChange = (event, data) => {
setSelectedItems(data.value);
if (data.value == "Select All") {
console.log(data);
console.log(event.target);
}
};
return (
<Dropdown
placeholder="Skills"
clearable
fluid
multiple
selection
options={options}
onChange={onChange}
value={selectedItems}
label="Skills"
/>
);
};
export default DropdownExampleMultipleSelection;

You need to check for the last selected items with event.target.textContent and add all options if this is selected.
const onChange = (event, data) => {
if(event.target.textContent === 'Select All') {
setSelectedItems(data.options.map(d => d.value))
} else {
setSelectedItems(data.value);
}
};

Related

Antd Tree component, how to add cache data

I have a problem with the Tree component of the Antd library. The problem is presented on the video. Namely that the component after changing the data tree renders anew and after selecting an option the previous ones are cleared. Does anyone have any idea how to solve this, so that after changing the data tree, the previous options that were selected are still selected?
import React, { useState } from 'react';
import { Tree } from 'antd';
import { Wrapper, TreeContainer } from './Tree.styled';
const treeData = [
{
title: '0-1',
key: '0-1',
children: [
{ title: '0-1-0-0', key: '0-0-0-0', },
{ title: '0-1-0-1', key: '0-0-0-1' },
{ title: '0-1-0-2', key: '0-0-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
{
title: '0-3',
key: '0-3',
children: [
{ title: '0-2-0-0', key: '0-2-0-0', },
{ title: '0-2-0-1', key: '0-2-0-1' },
{ title: '0-2-0-2', key: '0-2-0-2' },
],
},
{
title: '0-4',
key: '0-4',
children: [
{ title: '0-3-0-0', key: '0-3-0-0', },
{ title: '0-3-0-1', key: '0-3-0-1' },
{ title: '0-3-0-2', key: '0-3-0-2' },
],
},
{
title: '0-5',
key: '0-5',
children: [
{ title: '0-4-0-0', key: '0-4-0-0', },
{ title: '0-4-0-1', key: '0-4-0-1' },
{ title: '0-4-0-2', key: '0-4-0-2' },
],
},
];
const AntdTree = () => {
const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
const [optionValue, setOptionValue] = useState<any>();
const tree = treeData.filter(filterValue => filterValue.key == (!!optionValue ? optionValue : filterValue.key)).map(data => data)
const onCheck = (checkedKeysValue: any) => {
console.log('onCheck', checkedKeysValue);
setCheckedKeys(checkedKeysValue);
};
return (
<>
<Wrapper>
<TreeContainer>
<select value={optionValue} onChange={e => setOptionValue(e.target.value)} >
<option value={'0-1'}>0-1</option>
<option value={'0-2'}>0-2</option>
<option value={'0-3'}>0-3</option>
<option value={'0-4'}>0-4</option>
<option value={'0-5'}>0-5</option>
</select>
<button onClick={() => setOptionValue('')} >Delete</button>
<Tree
checkable
onCheck={onCheck}
checkedKeys={checkedKeys}
treeData={tree}
/>
</TreeContainer>
</Wrapper>
</>
);
};
export default AntdTree;
Link to video with problem: https://youtu.be/BLEzQck3cZo
Thanks for your help !๐Ÿ˜Š
onCheck callback in your case rewrite new values. You can save previous values using prevState in useState hook like so:
const onCheck = (checkedKeysValue: React.Key[], info: any) => {
console.log('onCheck', checkedKeysValue);
console.log('info', info);
if (info.checked) { // handle check case
setCheckedKeys(prevState => [...prevState, ...checkedKeysValue]);
} else { // handle uncheck case
setCheckedKeys(checkedKeysValue);
}
};

How to implement AddAdiditions in React Sematic UI using Hooks?

I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI.
Sematic UI Dropdown ALlowAdditions
I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.
import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 'English', text: 'English', value: 'English' },
{ key: 'French', text: 'French', value: 'French' },
{ key: 'Spanish', text: 'Spanish', value: 'Spanish' },
{ key: 'German', text: 'German', value: 'German' },
{ key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]
class DropdownExampleAllowAdditions extends Component {
state = { options }
handleAddition = (e, { value }) => {
this.setState((prevState) => ({
options: [{ text: value, value }, ...prevState.options],
}))
}
handleChange = (e, { value }) => this.setState({ currentValue: value })
render() {
const { currentValue } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Language'
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>
)
}
}
export default DropdownExampleAllowAdditions
Any help would be greatly appreciated. Thanks in advance :)
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "English", text: "English", value: "English" },
{ key: "French", text: "French", value: "French" },
{ key: "Spanish", text: "Spanish", value: "Spanish" },
{ key: "German", text: "German", value: "German" },
{ key: "Chinese", text: "Chinese", value: "Chinese" }
];
const DropDownWithHooks = () => {
const [dropDownOptions, setDropDownOptions] = useState(options);
const [currentValue, setCurrentValue] = useState("");
const handleAddition = (e, { value }) => {
setDropDownOptions((prevOptions) => [
{ text: value, value },
...prevOptions
]);
};
const handleChange = (e, { value }) => setCurrentValue(value);
return (
<Dropdown
options={dropDownOptions}
placeholder="Choose Language"
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={handleAddition}
onChange={handleChange}
/>
);
};
export default DropDownWithHooks;
Working Sandbox

How to select the desired input field for filtering in React Data Grid

I am trying to write some tests using Cypress with Reactjs (both latest versions). It seems like there is nothing I can select these input fields of filtering because they all look the same. Is there a way to put id/class names to these fields? I am both new to React and Cypress. Thanks
https://codesandbox.io/s/w6jvml4v45?from-embed=&file=/src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import ReactDataGrid from "react-data-grid";
import { Toolbar, Data } from "react-data-grid-addons";
import createRowData from "./createRowData";
import "./styles.css";
const defaultColumnProperties = {
filterable: true,
width: 120
};
const selectors = Data.Selectors;
const columns = [
{
key: "id",
name: "ID"
},
{
key: "title",
name: "Title"
},
{
key: "firstName",
name: "First Name"
},
{
key: "lastName",
name: "Last Name"
},
{
key: "email",
name: "Email"
},
{
key: "street",
name: "Street"
},
{
key: "zipCode",
name: "ZipCode"
},
{
key: "date",
name: "Date"
},
{
key: "jobTitle",
name: "Job Title"
},
{
key: "catchPhrase",
name: "Catch Phrase"
},
{
key: "jobArea",
name: "Job Area"
},
{
key: "jobType",
name: "Job Type"
}
].map(c => ({ ...c, ...defaultColumnProperties }));
const ROW_COUNT = 50;
const handleFilterChange = filter => filters => {
const newFilters = { ...filters };
if (filter.filterTerm) {
newFilters[filter.column.key] = filter;
} else {
delete newFilters[filter.column.key];
}
return newFilters;
};
function getRows(rows, filters) {
return selectors.getRows({ rows, filters });
}
function Example({ rows }) {
const [filters, setFilters] = useState({});
const filteredRows = getRows(rows, filters);
return (
<ReactDataGrid
columns={columns}
rowGetter={i => filteredRows[i]}
rowsCount={filteredRows.length}
minHeight={500}
toolbar={<Toolbar enableFilter={true} />}
onAddFilter={filter => setFilters(handleFilterChange(filter))}
onClearFilters={() => setFilters({})}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example rows={createRowData(50)} />, rootElement);
I would Use This specific attribute syntax to select them by key value:
cy.get(`input[key="${targetValue}"]`)
.then(element => {
//My code
})

How to convert function component to class component in fluent UI?

I am creating multi select drop down in Office fabrics.I saw the code.It contain the functional component.I want to change in class component.and How can we store the selected options in state variable?
please guide me.I am new in spfx share-point.
Code given below:-
import * as React from 'react';
import { Dropdown, DropdownMenuItemType, IDropdownOption, IDropdownStyles } from 'office-ui-fabric-react/lib/Dropdown';
const dropdownStyles: Partial<IDropdownStyles> = { dropdown: { width: 300 } };
const DropdownControlledMultiExampleOptions = [
{ key: 'fruitsHeader', text: 'Fruits', itemType: DropdownMenuItemType.Header },
{ key: 'apple', text: 'Apple' },
{ key: 'banana', text: 'Banana' },
{ key: 'orange', text: 'Orange', disabled: true },
{ key: 'grape', text: 'Grape' },
{ key: 'divider_1', text: '-', itemType: DropdownMenuItemType.Divider },
{ key: 'vegetablesHeader', text: 'Vegetables', itemType: DropdownMenuItemType.Header },
{ key: 'broccoli', text: 'Broccoli' },
{ key: 'carrot', text: 'Carrot' },
{ key: 'lettuce', text: 'Lettuce' },
];
export const DropdownControlledMultiExample: React.FunctionComponent = () => {
const [selectedKeys, setSelectedKeys] = React.useState<string[]>([]);
const onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
if (item) {
setSelectedKeys(
item.selected ? [...selectedKeys, item.key as string] : selectedKeys.filter(key => key !== item.key),
);
}
};
return (
<Dropdown
placeholder="Select options"
label="Multi-select controlled example"
selectedKeys={selectedKeys}
onChange={onChange}
multiSelect
options={DropdownControlledMultiExampleOptions}
styles={dropdownStyles}
/>
);
};
You can do the following:
export class DropdownControlledMultiExample extends React.Component {
state = {
selectedKeys: []
}
onChange = (event: React.FormEvent<HTMLDivElement>, item: IDropdownOption): void => {
if (item) {
this.setState({
selectedKeys:
item.selected
? [...this.state.selectedKeys, item.key as string]
: this.state.selectedKeys.filter(key => key !== item.key),
});
}
};
render() {
return (
<Dropdown
placeholder="Select options"
label="Multi-select controlled example"
selectedKeys={this.state.selectedKeys}
onChange={this.onChange}
multiSelect
options={DropdownControlledMultiExampleOptions}
styles={dropdownStyles}
/>
);
}
};

Updating React-Select menu with setState?

I am trying to get React-Select to display a different dropdown menu list based on the user input:
const helpOptions = [
{ value: "user", label: "u:<String> User Operator" },
{ value: "day", label: "d:<Number> Date Operator" },
{ value: "week", label: "w:<Number> Week Operator" },
{ value: "month", label: "m:<Number> Month Operator" },
{ value: "bracket", label: "() Brackets Operator" },
{ value: "and", label: "&& AND Operator" },
{ value: "or", label: "|| OR Operator" },
{ value: "not", label: "~ NOT Operator" }
];
const userOptions = [
{ value: "john", label: "u:John" },
];
class Field extends Component {
state = {
menu: userOptions,
value: ""
};
onInputChange = e => {
if (e.substring(0, 1) === "?") {
this.setState(
{
menu: helpOptions,
value: e
},
() => {
console.log(this.state.menu);
}
);
} else {
this.setState({
menu: []
});
}
};
render() {
const { menu, value } = this.state;
console.log("rendering");
console.log(menu);
return (
<Select
isMulti
value={value}
options={menu}
onInputChange={this.onInputChange}
/>
);
}
}
The desired behavior is if the first character of the text entered into the search field is a '?' the menu will populate with the const of helpOptions. Otherwise it would be (for now) empty.
Codesandbox: https://codesandbox.io/s/runtime-sun-cfg71
From the console logs, I seem to be getting the values and the rendering seems to be working. However, I am still getting 'No Option' as a response from the React-Select component.
How can I dynamically change the React-Select menu items based on the user's input?
Update
If you want your state to update after calling setState you need use a function that will work only after updating the state:
this.setState(state => ({
...state,
menu: helpOptions
}));
First of all you need to call a constructor in your component. Secondly, in documentation to react-select prop value doesn't exist. Thirdly, itโ€™s good practice to copy your state before changing.
Here is a valid code:
import React, { Component } from "react";
import Select from "react-select";
import "./styles.css";
const helpOptions = [
{ value: "user", label: "u:<String> User Operator" },
{ value: "day", label: "d:<Number> Date Operator" },
{ value: "week", label: "w:<Number> Week Operator" },
{ value: "month", label: "m:<Number> Month Operator" },
{ value: "bracket", label: "() Brackets Operator" },
{ value: "and", label: "&& AND Operator" },
{ value: "or", label: "|| OR Operator" },
{ value: "not", label: "~ NOT Operator" }
];
const userOptions = [
{ value: "john", label: "u:John" },
{ value: "stan", label: "d:Stan" },
{ value: "addison", label: "w:Addison" },
{ value: "dionis", label: "m:Dionis" }
];
class Field extends Component {
constructor(props) {
super(props);
this.state = {
menu: userOptions,
value: ""
};
}
onInputChange = e => {
if (e.substring(0, 1) === "?") {
console.log("help");
this.setState({
...this.state,
menu: helpOptions
});
} else {
this.setState({
...this.state,
menu: userOptions
});
}
};
render() {
const { menu, value } = this.state;
return <Select isMulti options={menu} onInputChange={this.onInputChange} />;
}
}
export default Field;
Here is an example on codesandbox.

Resources