React Rails Passing props to React Select - javascript

I'm trying to pass props from my Rails database to a React Select component using React rails, but the text is appearing invisible within the select option.
View:
= react_component('SelectSearch', options: Course.all.as_json(only: [:title]))
React select component:
import React from 'react';
import Select from 'react-select';
class SelectSearch extends React.Component {
constructor(props) {
super(props)
}
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={this.props.options}
/>
);
}
}
export default SelectSearch;
When something in the select is clicked, it console logs, for example:
Option selected: {title: "English"}
But opening the select, its completely blank. There is obviously an option there that can be clicked, but nothing is displayed. Likewise for searching, no options are displayed.
I know this is because I'm passing the props incorrectly, or handling the data incorrectly, I don't want {title: "English"} I just want English but not sure how to filter this correctly.

See the react-select example:
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const MyComponent = () => (
<Select options={options} />
)
Your options contains unneeded 'title' attribute and not contains 'value' and 'label'. Fix it.

Took me a while to figure it out, but got this working:
= react_component('SelectSearch', data: Course.all.as_json(only: [:title]))
import React from 'react';
import Select from 'react-select';
class SelectSearch extends React.Component {
constructor(props) {
super(props);
}
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={this.props.data}
getOptionLabel={(option) => option.title}
getOptionValue={(option) => option.title}
/>
);
}
}
export default SelectSearch;
React-select expects a value and a label and this seems to be the easiest way to pass it.

Related

How to pass dropdown value to state/get request? React

Hey react newbie here!
I am trying to use a select/option value from a drop down to be used in a get request { selectedOption }.
I am unsure how to pass the selectedOption into my main state/component to be used in the get request.
Can anybody point me in the right direction please? <3
Constructor/state:
public constructor(props) {
super(props);
this.state = {
documents: [],
selectedOption: null
};
}
Get request:
public getDocuments() {
axios
.get("https://bpk.sharepoint.com/_api/search/query?querytext='Colour:" + this.state.selectedOption + "'&trimduplicates=true&rowsperpage=100&rowlimit=1000",
{ params:{},
headers: { 'accept': 'application/json;odata=verbose' }
})
....
}
Render:
public render(): React.ReactElement<IKimProps> {
let { documents, selectedOption } = this.state;
return (
<div className={ styles.kim }>
<Selecter></Selecter>
<br/><br/>
{this.renderDocuments()}
</div>
);
}
}
Selector Component (Not in main app, in the main app its a component called <.Selecter.><./Selecter.>):
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'red', label: 'red' },
{ value: 'blue', label: 'blue' },
{ value: 'green', label: 'green' }
];
class Selecter 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}
/>
);
}
}
export default Selecter;
The issue here is that you're setting the state of Selecter, but never bubbling that up to the parent class. The general way you do this is via a prop passed to Selecter that sets the parent state:
Parent.js:
...
public setSelectedOption(selectedOption){
this.setState({ selectedOption: selectedOption });
// or this.setState({ selectedOption }); (whichever works)
}
public render(): React.ReactElement<IKimProps> {
...
<Selecter onChange={this.setSelectedOption.bind(this)}></Selecter>
}
Then, handle the passed function in Selecter.js:
class Selecter extends React.Component {
...
handleChange = selectedOption => {
this.setState({ selectedOption });
if(this.props.onChange){
this.props.onChange(selectedOption);
}
};
}

Get consolidated data from all the child components in the form of an object inside a parent component : React JS

I am implementing a setting page for an application. For each setting I have implemented a slider that has enabled(green) or disabled(red) state. But parent's settings is read only and is calculated based on the values of its children.
Parent's setting is derived as follows: If all children are red, parent stays red ; If all are green parent stays green; If at-least one of child is green then parent stays grey(Pending).
These settings are grouped something like this:
Parent Feature 1 : (read-only-toggle)
Setting 1 (Toggle)
Setting 2 (Toggle)
Parent Feature 2: (read-only-toggle)
Setting 1 (Toggle)
Setting 2 (Toggle)
And in the end there is also a button, that gives me a consolidated values of all parent and children. But so far I was able to do only with one parent and 2 children.
Can someone help with an approach of getting consolidated values of all the settings in one place(Like a super parent component where all these settings are configured).
For this , I am using react-multi-toggle for this toggle switch.
Help would be really appreciated.
Code Sandbox: https://codesandbox.io/s/react-multi-toggle-solution-perfect-v9bi5
App
import React from "react";
import ChildSwitch from "./ChildSwitch";
import ParentSwitch from "./ParentSwitch";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
parentVal: "disabled",
switch1Val: "enabled",
switch2Val: "disabled"
};
}
componentDidMount() {
this.setParentSwitchValue();
}
onGetChildSwitchValues = () => {
console.log(this.state);
};
setChildSwitchValue = (whichSwitch, selected) => {
this.setState(
prevState => ({ ...prevState, [whichSwitch]: selected }),
this.setParentSwitchValue
);
};
setParentSwitchValue = () => {
const { switch1Val, switch2Val } = this.state;
const switchStates = [switch1Val, switch2Val];
let parent = "pending";
if (switchStates.every(val => val === "enabled")) {
parent = "enabled";
}
if (switchStates.every(val => val === "disabled")) {
parent = "disabled";
}
this.setState(prevState => ({ ...prevState, parentVal: parent }));
};
render() {
const { parentVal, switch1Val, switch2Val } = this.state;
return (
<>
<div className="boxed">
Parent Setting 1 :{" "}
<ParentSwitch
parentSwitch={parentVal}
onSelect={this.setParentSwitchValue}
/>
Setting 1:
<ChildSwitch
switchName={"switch1Val"}
selected={switch1Val}
onSelect={this.setChildSwitchValue}
/>
Setting 2:
<ChildSwitch
switchName={"switch2Val"}
selected={switch2Val}
onSelect={this.setChildSwitchValue}
/>
</div>
<button onClick={this.onGetChildSwitchValues}>Get All Values</button>
</>
);
}
}
ChildSetting
import MultiToggle from "react-multi-toggle";
import React from "react";
export default class ChildSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
options: [
{
displayName: "Disabled",
value: "disabled"
},
{
displayName: "Enabled",
value: "enabled"
}
]
};
}
onSelectOption = selected => {
this.props.onSelect(this.props.switchName, selected);
};
render() {
const { options } = this.state;
const { selected } = this.props;
return (
<MultiToggle
options={options}
selectedOption={selected}
onSelectOption={this.onSelectOption}
/>
);
}
}
Parent Setting
import MultiToggle from "react-multi-toggle";
import React from "react";
import "react-multi-toggle/style.css";
export default class ParentSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
options: [
{
displayName: "Disabled",
value: "disabled"
},
{
displayName: "Pending",
value: "pending"
},
{
displayName: "Enabled",
value: "enabled"
}
]
};
}
render() {
const { options } = this.state;
return (
<MultiToggle
options={options}
selectedOption={this.props.parentSwitch}
onSelectOption={() => {}}
/>
);
}
}
I will suggest that you group your child and parent under one component. Let say we name it Settings. Then, we create another component that will render a list of Settings and a button. This last component will hold the values of all Settings. Finally, each time the value of a Setting Component Change, we update the list. Checkout a sample working app here.
App Component
export default class App extends PureComponent {
state = {};
onSettingChange = (settingId, setting) => {
this.setState(prevState => ({
...prevState,
[settingId]: setting
}));
};
onGetSettingValues = () => {
console.log(this.state);
};
render() {
return (
<Fragment>
<Setting id="setting1" onChange={this.onSettingChange} />
<Setting id="setting2" onChange={this.onSettingChange} />
<button onClick={this.onGetSettingValues}>Get All Values</button>
</Fragment>
);
}
}
Setting Component
import React, { PureComponent, Fragment } from "react";
import ChildSwitch from "./ChildSwitch";
import ParentSwitch from "./ParentSwitch";
export default class Setting extends PureComponent {
state = {
parentVal: "disabled",
switch1Val: "enabled",
switch2Val: "disabled"
};
componentDidMount() {
this.setParentSwitchValue();
}
setChildSwitchValue = (whichSwitch, selected) => {
this.setState(
prevState => ({ ...prevState, [whichSwitch]: selected }),
this.setParentSwitchValue
);
};
handleChange = () => {
const { id, onChange } = this.props;
onChange(id, this.state);
};
setParentSwitchValue = () => {
const { switch1Val, switch2Val } = this.state;
const switchStates = [switch1Val, switch2Val];
let parent = "pending";
if (switchStates.every(val => val === "enabled")) {
parent = "enabled";
}
if (switchStates.every(val => val === "disabled")) {
parent = "disabled";
}
this.setState(
prevState => ({ ...prevState, parentVal: parent }),
this.handleChange
);
};
render() {
const { parentVal, switch1Val, switch2Val } = this.state;
return (
<Fragment>
<div className="boxed">
Parent Setting 1
<ParentSwitch
parentSwitch={parentVal}
onSelect={this.setParentSwitchValue}
/>
Setting 1:
<ChildSwitch
switchName={"switch1Val"}
selected={switch1Val}
onSelect={this.setChildSwitchValue}
/>
Setting 2:
<ChildSwitch
switchName={"switch2Val"}
selected={switch2Val}
onSelect={this.setChildSwitchValue}
/>
</div>
</Fragment>
);
}
}
Put all your states into a single context hook.
const SettingsContext = createContext({state1, state2/* all your states in here*/);
You'll then wrap the whole thing into this context as such:
<SettingsContext.Provider>
<App/>
</SettingsContext.Provider>
Now you can access the state in any of the children, parents etc. I suggest however not storing things like "disabled", "enabled" as strings, but rather store states as { enabled: true, pending: false}

Prevent child's state from reset after parent component state changes also get the values of all child components:ReactJS+ Typescript

I am a bit new to react and I am stuck in this situation where I am implementing custom dropdown filter for a table in react. I have set of dropdown values for each column and there is a Apply button.
I have maintained a child component for this which takes in drop down values and sends the selected one's back to parent. Then I call a back-end API that gives me filtered data which in-turn sets parents state . The problem here is the checkbox values inside dropdown is lost after I get the data and set the parent state.
Each child components has as a set of checkboxes , an Apply and a clear button. So on click of Apply , I have to send the checked one's to the parent or in general whichever the checked one's without losing the previous content.
I am unable to understand why am I losing the checkbox values?
It would be of great help if someone can help me out with this
Sand box: https://codesandbox.io/s/nervous-elgamal-0zztb
I have added the sandbox link with proper comments. Please have a look. I am a bit new to react.
Help would be really appreciated
Parent
import * as React from "react";
import { render } from "react-dom";
import ReactTable from "react-table";
import "./styles.css";
import "react-table/react-table.css";
import Child from "./Child";
interface IState {
data: {}[];
columns: {}[];
selectedValues: {};
optionsForColumns: {};
}
interface IProps {}
export default class App extends React.Component<IProps, IState> {
// Here I have hardcoded the values, but data and optionsForColumns comes from the backend and it is set inside componentDidMount
constructor(props: any) {
super(props);
this.state = {
data: [
{ firstName: "Jack", status: "Submitted", age: "14" },
{ firstName: "Simon", status: "Pending", age: "15" }
],
selectedValues: {},
columns: [],
optionsForColumns: {
firstName: [{ Jack: "4" }, { Simon: "5" }],
status: [{ Submitted: "5" }, { Pending: "7" }]
}
};
}
// Get the values for checkboxes that will be sent to child
getValuesFromKey = (key: any) => {
let data: any = this.state.optionsForColumns[key];
let result = data.map((value: any) => {
let keys = Object.keys(value);
return {
field: keys[0],
checked: false
};
});
return result;
};
// Get the consolidated values from child and then pass it for server side filtering
handleFilter = (fieldName: any, selectedValue: any, modifiedObj: any) =>
{
this.setState(
{
selectedValues: {
...this.state.selectedValues,
[fieldName]: selectedValue
}
},
() => this.handleColumnFilter(this.state.selectedValues)
);
};
// Function that will make server call based on the checked values from child
handleColumnFilter = (values: any) => {
// server side code for filtering
// After this checkbox content is lost
};
// Function where I configure the columns array for the table . (Also data and column fiter values will be set here, in this case I have hardcoded inside constructor)
componentDidMount() {
let columns = [
{
Header: () => (
<div>
<div>
<Child
key="firstName"
name="firstName"
options={this.getValuesFromKey("firstName")}
handleFilter={this.handleFilter}
/>
</div>
<span>First Name</span>
</div>
),
accessor: "firstName"
},
{
Header: () => (
<div>
<div>
<Child
key="status"
name="status"
options={this.getValuesFromKey("status")}
handleFilter={this.handleFilter}
/>
</div>
<span>Status</span>
</div>
),
accessor: "status",
},
{
Header: "Age",
accessor: "age"
}
];
this.setState({ columns });
}
//Rendering the data table
render() {
const { data, columns } = this.state;
return (
<div>
<ReactTable
data={data}
columns={columns}
/>
</div>
);
}
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Child
import * as React from "react";
import { Button, Checkbox, Icon } from "semantic-ui-react";
interface IProps {
options: any;
name: string;
handleFilter(val1: any, val2: any, val3: void): void;
}
interface IState {
showList: boolean;
selected: [];
checkboxOptions: any;
}
export default class Child extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
selected: [],
showList: false,
checkboxOptions: this.props.options.map((option: any) => option.checked)
};
}
// Checkbox change handler
handleValueChange = (event: React.FormEvent<HTMLInputElement>, data: any) => {
const i = this.props.options.findIndex(
(item: any) => item.field === data.name
);
const optionsArr = this.state.checkboxOptions.map(
(prevState: any, si: any) => (si === i ? !prevState : prevState)
);
this.setState({ checkboxOptions: optionsArr });
};
//Passing the checked values back to parent
passSelectionToParent = (event: any) => {
event.preventDefault();
const result = this.props.options.map((item: any, i: any) =>
Object.assign({}, item, {
checked: this.state.checkboxOptions[i]
})
);
const selected = result
.filter((res: any) => res.checked)
.map((ele: any) => ele.field);
console.log(selected);
this.props.handleFilter(this.props.name, selected, result);
};
//Show/Hide filter
toggleList = () => {
this.setState(prevState => ({ showList: !prevState.showList }));
};
//Rendering the checkboxes based on the local state, but still it gets lost after filtering happens
render() {
let { showList } = this.state;
let visibleFlag: string;
if (showList === true) visibleFlag = "visible";
else visibleFlag = "";
return (
<div>
<div style={{ position: "absolute" }}>
<div
className={"ui scrolling dropdown column-settings " + visibleFlag}
>
<Icon className="filter" onClick={this.toggleList} />
<div className={"menu transition " + visibleFlag}>
<div className="menu-item-holder">
{this.props.options.map((item: any, i: number) => (
<div className="menu-item" key={i}>
<Checkbox
name={item.field}
onChange={this.handleValueChange}
label={item.field}
checked={this.state.checkboxOptions[i]}
/>
</div>
))}
</div>
<div className="menu-btn-holder">
<Button size="small" onClick={this.passSelectionToParent}>
Apply
</Button>
</div>
</div>
</div>
</div>
</div>
);
}
}
This appears to be a case of state being managed in an inconvenient way. Currently, the state is managed at the Child level, but it would be easier to manage at the Parent level. This is known as lifting state up in React.
The gist - the shared state is managed in the Parent component, and it's updated by calling a function passed to the Child component. When Apply is clicked, the selected radio value is passed up to the Parent, which merges the new selection into the shared state.
I have created a minimal example of your code, showing how we can lift state up from the Child to the Parent component. I'm also using a few new-ish features of React, like useState to simplify the Child component.
// Child Component
const Child = ({name, options, updateSelections}) => {
const [selected, setSelected] = React.useState([]);
const handleChange = (event) => {
let updated;
if (event.target.checked) {
updated = [...selected, event.target.value];
} else {
updated = selected.filter(v => v !== event.target.value);
}
setSelected(updated);
}
const passSelectionToParent = (event) => {
event.preventDefault();
updateSelections(name, selected);
}
return (
<form>
{options.map(item => (
<label for={name}>
<input
key={name}
type="checkbox"
name={item}
value={item}
onChange={handleChange}
/>
{item}
</label>
))}
<button onClick={passSelectionToParent}>Apply</button>
</form>
)
}
// Parent Component
class Parent extends React.Component {
constructor(props) {
super(props);
this.fields = ["firstName", "status"],
this.state = {
selected: {}
};
}
getValuesFromKey = (data, key) => {
return data.map(item => item[key]);
}
updateSelections = (name, selection) => {
this.setState({
selected: {...this.state.selected, [name]: selection}
}, () => console.log(this.state.selected));
}
render() {
return (
<div>
{this.fields.map(field => (
<Child
key={field}
name={field}
options={this.getValuesFromKey(this.props.data, field)}
updateSelections={this.updateSelections}
/>
))}
</div>
)
}
}
const data = [
{ firstName: "Jack", status: "Submitted" },
{ firstName: "Simon", status: "Pending" },
{ firstName: "Pete", status: "Approved" },
{ firstName: "Lucas", status: "Rejected" }
];
ReactDOM.render(<Parent data={data}/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Your checkbox values are only lost when you hide/show the table, as the table goes out of
DOM the state of it and it's children are lost. When the table is mounted to DOM, Child
component is mounted again initializing a new state taking checkbox values from
getValuesFromKey method of which returns false by default clearing checkbox ticks.
return {
field: keys[0],
checked: false
};
Stackblitz reproducing the issue.
You have to set checkbox values checking the selectedValues object to see if it was selected.
return {
field: keys[0],
checked: this.state.selectedValues[key] && this.state.selectedValues[key].includes(keys[0]),
};

onChange is not triggering in react js

I use the dropdown in react js app but onChange is not triggering
my code is
import React from "react";
import PropTypes from "prop-types";
import Dropdown from 'react-dropdown';
const options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two', className: 'myOptionClassName' },
];
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
quan = (event)=> {
console.log("Option selected:");
this.setState({ value: event.target.value });
};
render() {
return(
<b><Dropdown className="dropdownCss" options={options} onChange={e =>
this.quan(e.target.value)} /></b>
);
}
when I click the items in dropdown it shows the error
"TypeError: Cannot read property 'quan' of undefined"
I'm a newbie to react
thanks in advance
There is no issue with the react-dropdown library. Here is the code sandbox that I've set up and corrected OP's code. It works.
import React from "react";
import Dropdown from "react-dropdown";
import "react-dropdown/style.css";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two", className: "myOptionClassName" }
];
const defaultOption = options[0];
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedValue: ""
};
}
quan = value => {
this.setState({ selectedValue: value });
};
render() {
return (
<Dropdown options={options} value={defaultOption} onChange={this.quan} />
);
}
}
export default WebDashboardPage;
You should just do it this way:
<Dropdown className="dropdownCss" options={options} onChange={this.quan} />
Try this:
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' }
this.quan = this.quan.bind(this);
}
quan(event) {
console.log("Option selected:");
this.setState({ value: event.target.value });
};
render() {
return(
<div><Dropdown className="dropdownCss" options={options} onChange={this.quan} /></div>
);
}
It seems the issue is with the react-dropdown component itself. You'll need to file an issue there.
react-dropdown component might not be using this.props.onChange somewhere or might be using problematically.
Or, it's probably, the component requires value state which have not defined?
this.state = {
value: ''
}
And was causing the issue?
The dropdown dependency you are using does not fire onChange with event as argument instead it fires onChange with the selected option.Try changing
onChange={e =>
this.quan(e.target.value)}
to
onChange={this.quan}
and change quan to
quan = (selectedOption)=> {
console.log("Option selected:"+selectedOption.value);
this.setState({ value: selectedOption.value });
};
I have tried it on my machine and it wroks perfectly. Also next important thing is don't put options the way you are doing instead put it on state. my final code is
class WebDashboardPage extends Component {
constructor(props) {
super(props);
const options = [
{
value: 'one',
label: 'One'
}, {
value: 'two',
label: 'Two',
className: 'myOptionClassName'
}
];
this.state = {options}
}
quan = (selectedOption) => {
console.log("Option selected:" + selectedOption.value);
this.setState({value: selectedOption.value});
};
render() {
return (<b><Dropdown className="dropdownCss" options={this.state.options} onChange={this.quan}/></b>);
}
}
I only did a little refactoring to the code. The main change is in how Dropdown handles change. When you pass in a function to handleChange, Dropdown calls the function internally and passes the selected object to it, so you all you needed to do was create a handler method that has one parameter which you'll use to update the state. I also set an initial state for value. Here's is a demo https://codesandbox.io/s/4qz7n0okyw
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
import Dropdown from "react-dropdown";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two", className: "myOptionClassName" }
];
class WebDashboardPage extends Component {
state = {
value: {}
};
quan = value => {
console.log("Option selected:", value);
this.setState({ value });
};
render() {
return (
<Fragment>
<Dropdown
className="dropdownCss"
options={options}
onChange={this.quan}
/>
</Fragment>
);
}
}
export default WebDashboardPage;
Change to
onChange={this.quan}, also in the initial state you should state your this.state.value
this.state = {
value: ''
}
also try to learn it on html element, not on jsx

How to programmatically clear/reset React-Select?

ReactSelect V2 and V3 seems to have several props like clearValue, resetValue and setValue. Whatever I'm trying, I'm not able to clear the selections programmatically. resetValue seems not to be accessible from the outside.
selectRef.setValue([], 'clear')
// or
selectRef.clearValue()
This does not clear the current selection.
Do I miss something here or is it not fully implemented yet?
I came across this problem myself and managed to fix it by passing a key to the React-Select component, with the selected value appended to it. This will then force the ReactSelect to re-render itself when the selection is updated.
I hope this helps someone.
import ReactSelect from 'react-select';
...
<ReactSelect
key={`my_unique_select_key__${selected}`}
value={selected || ''}
...
/>
If you're using react-select you can try to pass null to value prop.
For example:
import React from "react";
import { render } from "react-dom";
import Select from "react-select";
class App extends React.Component {
constructor(props) {
super(props);
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two" }
];
this.state = {
select: {
value: options[0], // "One" as initial value for react-select
options // all available options
}
};
}
setValue = value => {
this.setState(prevState => ({
select: {
...prevState.select,
value
}
}));
};
handleChange = value => {
this.setValue(value);
};
handleClick = () => {
this.setValue(null); // here we reset value
};
render() {
const { select } = this.state;
return (
<div>
<p>
<button type="button" onClick={this.handleClick}>
Reset value
</button>
</p>
<Select
name="form-field-name"
value={select.value}
onChange={this.handleChange}
options={select.options}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Here's a working example of this.
You can clear the value of react select using the ref.
import React, { useRef } from "react";
import Select from "react-select";
export default function App() {
const selectInputRef = useRef();
const onClear = () => {
selectInputRef.current.select.clearValue();
};
return (
<div className="App">
<h1>Select Gender</h1>
<Select
ref={selectInputRef}
options={[
{ value: "male", label: "Male" },
{ value: "female", label: "Female" }
]}
/>
<button onClick={onClear}>Clear Value</button>
</div>
);
}
Here is the CodeSandbox link
Just store the value in the state, and change the state programmatically using componentDidUpdate etc...
class Example extends Component {
constructor() {
super()
}
state = {
value: {label: 'Default value', key : '001'}
}
render() {
return(
<Select
...
value={this.state.value}
...
/>
)
)}
Note: 'value' should be an object.
A simple option would be to pass null to the value prop.
<Select value={null} />
This is my working implementation of a React-Select V3 cleared programmatically with Hooks.
You can play with it in the CodeSandbox DEMO. Any feedback is welcome.
const initialFormState = { mySelectKey: null };
const [myForm, setMyForm] = useState(initialFormState);
const updateForm = value => {
setMyForm({ ...myForm, mySelectKey: value });
};
const resetForm = () => {
setMyForm(initialFormState);
};
return (
<div className="App">
<form>
<Select name = "mySelect"
options = {options}
value = {options.filter(({ value }) => value === myForm.mySelectKey)}
getOptionLabel = {({ label }) => label}
getOptionValue = {({ value }) => value}
onChange = {({ value }) => updateForm(value)} />
<p>MyForm: {JSON.stringify(myForm)}</p>
<input type="button" value="Reset fields" onClick={resetForm} />
</form>
</div>
);
If someone looking for solution using Hooks. React-Select V3.05:
const initial_state = { my_field: "" }
const my_field_options = [
{ value: 1, label: "Daily" },
{ value: 2, label: "Weekly" },
{ value: 3, label: "Monthly" },
]
export default function Example(){
const [values, setValues] = useState(initial_state);
function handleSelectChange(newValue, actionMeta){
setValues({
...values,
[actionMeta.name]: newValue ? newValue.value : ""
})
}
return <Select
name={"my_field"}
inputId={"my_field"}
onChange={handleSelectChange}
options={my_field_options}
placeholder={values.my_field}
isClearable={true}
/>
}
Along the top answer, please note that the value needs to be "null" and not "undefined" to clear properly.
If you check Select component in React Developers panel you will see that it is wrapped by another – State Manager. So you ref is basically ref to State manager, but not to Select itself.
Luckily, StateManager has state) and a value object which you may set to whatever you want.
For example (this is from my project, resetGroup is onClick handler that I attach to some button in DOM):
<Select onChange={this.handleGroupSelect}
options={this.state.groupsName.map(group =>
({ label: group, value: group }) )}
instanceId="groupselect"
className='group-select-container'
classNamePrefix="select"
placeholder={this.context.t("Enter name")}
ref={c => (this.groupSelect = c)}
/>
resetGroup = (e) => {
e.preventDefault()
this.setState({
selectedGroupName: ""
})
this.groupSelect.state.value.value = ""
this.groupSelect.state.value.label = this.context.t("Enter name")
}
For those who are working with function component, here's a basic demo of how you can reset the react select Based on some change/trigger/reduxValue.
import React, { useState, useEffect } from 'react';
import Select from 'react-select';
const customReactSelect = ({ options }) => {
const [selectedValue, setSelectedValue] = useState([]);
/**
* Based on Some conditions you can reset your value
*/
useEffect(() => {
setSelectedValue([])
}, [someReduxStateVariable]);
const handleChange = (selectedVal) => {
setSelectedValue(selectedVal);
};
return (
<Select value={selectedValue} onChange={handleChange} options={options} />
);
};
export default customReactSelect;
in v5, you can actually pass the prop isClearable={true} to make it clearable, which easily resets the selected value
You can set the value to null
const [selectedValue, setSelectedValue] = useState();
const [valueList, setValueList] = useState([]);
const [loadingValueList, setLoadingValueList] = useState(true);
useEffect(() => {
//on page load update valueList and Loading as false
setValueList(list);
loadingValueList(false)
}, []);
const onClear = () => {
setSelectedValue(null); // this will reset the selected value
};
<Select
className="basic-single"
classNamePrefix="select"
value={selectedValue}
isLoading={loadingValueList}
isClearable={true}
isSearchable={true}
name="selectValue"
options={valueList}
onChange={(selectedValue) =>
setSelectedValue(selectedValue)}
/>
<button onClick={onClear}>Clear Value</button>
react-select/creatable.
The question explicitly seeks a solution to react-select/creatable. Please find the below code, a simple answer and solution to the question. You may modify the code for your specific task.
import CreatableSelect from "react-select/creatable";
const TestAction = (props) => {
const { buttonLabelView, className } = props;
const selectInputRef = useRef();
function clearSelected() {
selectInputRef.current.select.select.clearValue();
}
const createOption = (label, dataId) => ({
label,
value: dataId,
});
const Options = ["C1", "C2", "C3", "C4"]?.map((post, id) => {
return createOption(post, id);
});
return (
<div>
<CreatableSelect
ref={selectInputRef}
name="dataN"
id="dataN"
className="selctInputs"
placeholder=" Select..."
isMulti
options={Options}
/>
<button onClick={(e) => clearSelected()}> Clear </button>
</div>
);
};
export default TestAction;
In case it helps anyone, this is my solution: I created a button to clear the selected value by setting state back to it's initial value.
<button onClick={() => this.clearFilters()} >Clear</button>
clearFilters(){
this.setState({ startTime: null })
}
Full code sample below:
import React from "react"
import Select from 'react-select';
const timeSlots = [
{ value: '8:00', label: '8:00' },
{ value: '9:00', label: '9:00' },
{ value: '10:00', label: '10:00' },
]
class Filter extends React.Component {
constructor(){
super();
this.state = {
startTime: null,
}
}
startTime = (selectedTime) => {
this.setState({ startTime: selectedTime });
}
clearFilters(){
this.setState({
startTime: null,
})
}
render(){
const { startTime } = this.state;
return(
<div>
<button onClick={() => this.clearFilters()} >Clear</button>
<Select
value={startTime}
onChange={this.startTime}
options={timeSlots}
placeholder='Start time'
/>
</div>
)
}
}
export default Filter
passing null in value attribute of the react-select will reset it.
if you are using formik then use below code to reset react-select value.
useEffect(()=>{
formik.setFieldValue("stateName", [])
},[])
Where stateName is html field name.
if you want to change value according to another dropdown/select (countryName) then pass that field value in useEffect array like below
useEffect(()=>{
formik.setFieldValue("stateName", [])
},[formik.values.countryName])
Zeeshan's answer is indeed correct - you can use clearValue() but when you do so, the Select instance isn't reset to your defaultValue prop like you might be thinking it will be. clearValue() returns a general Select... label with no data in value.
You probably want to use selectOption() in your reset to explicitly tell react-select what value/label it should reset to. How I wired it up (using Next.js, styled-components and react-select):
import { useState, useRef } from 'react'
import styled from 'styled-components'
import Select from 'react-select'
// Basic button design for reset button
const UIButton = styled.button`
background-color: #fff;
border: none;
border-radius: 0;
color: inherit;
cursor: pointer;
font-weight: 700;
min-width: 250px;
padding: 17px 10px;
text-transform: uppercase;
transition: 0.2s ease-in-out;
&:hover {
background-color: lightgray;
}
`
// Using style object `react-select` library indicates as best practice
const selectStyles = {
control: (provided, state) => ({
...provided,
borderRadius: 0,
fontWeight: 700,
margin: '0 20px 10px 0',
padding: '10px',
textTransform: 'uppercase',
minWidth: '250px'
})
}
export default function Sample() {
// State for my data (assume `data` is valid)
const [ currentData, setCurrentData ] = useState(data.initial)
// Set refs for each select you have (one in this example)
const regionOption = useRef(null)
// Set region options, note how I have `data.initial` set here
// This is so that when my select resets, the data will reset as well
const regionSelectOptions = [
{ value: data.initial, label: 'Select a Region' },
{ value: data.regionOne, label: 'Region One' },
]
// Changes data by receiving event from select form
// We read the event's value and modify currentData accordingly
const handleSelectChange = (e) => {
setCurrentData(e.value)
}
// Reset, notice how you have to pass the selected Option you want to reset
// selectOption is smart enough to read the `value` key in regionSelectOptions
// All you have to do is pass in the array position that contains a value/label obj
// In my case this would return us to `Select a Region...` label with `data.initial` value
const resetData = () => {
regionOption.current.select.selectOption(regionSelectOptions[0])
setCurrentData(data.initial)
}
// notice how my `UIButton` for the reset is separate from my select menu
return(
<>
<h2>Select a region</h2>
<Select
aria-label="Region select menu"
defaultValue={ regionSelectOptions[0] }
onChange={ event => handleDataChange(event) }
options={ regionSelectOptions }
ref={ regionOption }
styles={ selectStyles }
/>
<UIButton
onClick={ resetData }
>
Reset
</UIButton>
</>
)
}
Nether of the solution help me.
This work for me:
import React, { Component, Fragment } from "react";
import Select from "react-select";
import { colourOptions } from "./docs/data";
export default class SingleSelect extends Component {
selectRef = null;
clearValue = () => {
this.selectRef.select.clearValue();
};
render() {
return (
<Fragment>
<Select
ref={ref => {
this.selectRef = ref;
}}
className="basic-single"
classNamePrefix="select"
defaultValue={colourOptions[0]}
name="color"
options={colourOptions}
/>
<button onClick={this.clearValue}>clear</button>
</Fragment>
);
}
}
None of the top suggestions worked for me and they all seemed a bit over the top. Here's the important part of what worked for me
<Select
value={this.state.selected && Object.keys(this.state.selected).length ? this.state.selected : null},
onChange={this.handleSelectChange}
/>
StateManager is abolished now, at least after version 5.5.0.
Now if you use ref, you can just do it like this:
selectRef = null
<Select
...
ref={c => (selectRef=c)}
/>
clearValue = () => {
selectRef.clearValue();
};
Here this c would be the Select2 React Component
This bugged me so here it is:
React select uses arrays so you have to pass an empty array not null.
Using React's useState:
import ReactSelect from 'react-select'
const Example = () => {
const [val, setVal] = useState()
const reset = () => {
setVal([])
}
return <ReactSelect
value={val}/>
}
export default Example
Create a function called onClear, and setSelected to empty string.
Inside the handle submit function, call the onClear function.
This will work perfectly.
Example code:
const onClear = () => {
setSelected("");
};
const handleSubmit = ()=>{
1 your data first ......(what you are posting or updating)
2 onClear();
}
if you are using formik then use below code to reset react-select value.
useEffect(()=>{
formik.setFieldValue("stateName", [])
},[])
Where stateName is html field name.
if you want to change value according to another dropdown/select (countryName) then pass that field value in useEffect array like below
useEffect(()=>{
formik.setFieldValue("stateName", [])
},[formik.values.countryName])
I use redux-observable.
Initial state:
firstSelectData: [],
secondSelectData:[],
secondSelectValue: null
I create an action for filling first select. on change of first select, I call an action to fill second one.
In success of fill first select I set (secondSelectData to [], secondSelectValue to null)
In success of fill second select I set (secondSelectValue to null)
on change of second select, I call an action to update secondSelectValue with the new value selected

Categories

Resources