I'm currently stuck on trying to display the number of correct answers once the quiz is finished.
Basically, I have created a state that keeps track of the number of correct answers shown within the QuizItem component. If the user selected answer matches the correct answer, then the user selected answer turns to green and it will increase the state of correctCount (as seen in the code) to 1. This new value is then passed to the parent component of QuizItem which is QuizList.
/* eslint-disable react/prop-types */
import React from "react";
import AnswerButton from "../UI/AnswerButton";
import classes from "./QuizItem.module.css";
export default function QuizItem(props) {
const [correctCount, setCorrectCount] = React.useState(0)
function addToCorrectCount() {
setCorrectCount(correctCount + 1)
}
props.onSaveCorrectCountData(correctCount)
console.log(correctCount);
return (
<div>
<div key={props.id} className={classes.quizlist__quizitem}>
<h3 className={classes.quizitem__h3}>{props.question}</h3>
{props.choices.map((choice) => {
const styles = {
backgroundColor: choice.isSelected ? "#D6DBF5" : "white",
};
// React.useEffect(() => {
// if (choice.isSelected && choice.choice === choice.correct) {
// addToCorrectCount();
// }
// }, [choice.isSelected, choice.correct]);
function checkAnswerStyle() {
/* this is to indicate that the selected answer is right, makes button go green*/
if (choice.isSelected && choice.choice === choice.correct) {
addToCorrectCount()
return {
backgroundColor: "#94D7A2",
color: "#4D5B9E",
border: "none",
};
/* this is to indicate that the selected answer is wrong, makes button go red*/
} else if (choice.isSelected && choice.choice !== choice.correct) {
return {
backgroundColor: "#F8BCBC",
color: "#4D5B9E",
border: "none",
};
/* this is to highlight the right answer if a selected answer is wrong*/
} else if (choice.choice === choice.correct) {
return {
backgroundColor: "#94D7A2",
color: "#4D5B9E",
border: "none",
};
/* this is to grey out the incorrect answers*/
} else {
return {
color: "#bfc0c0",
border: "1px solid #bfc0c0",
backgroundColor: "white",
};
}
}
return (
<AnswerButton
key={choice.id}
onClick={() => {
props.holdAnswer(choice.id);
}}
style={props.endQuiz ? checkAnswerStyle() : styles}
>
{choice.choice}
</AnswerButton>
);
})}
</div>
</div>
);
}
// create a counter, and for every correct answer (green button), increase the counter by 1.
In the QuizList component, I have set another state to receive the incoming value from the QuizItem component and use this new value to display the number of correct answers once the check answers button has been clicked.
import React from "react";
import { nanoid } from "nanoid";
import QuizItem from "./QuizItem";
import Button from "../UI/Button";
import Card from "../UI/Card";
import classes from "./QuizList.module.css";
export default function QuizList(props) {
const [quiz, setQuiz] = React.useState([]);
const [endQuiz, setEndQuiz] = React.useState(false);
// const [newGame, setNewGame] = React.useState(false);
const [noOfCorrectAnswers, setNoOfCorrectAnswers] = React.useState()
function addCorrectCountHandler(correctCount) {
setNoOfCorrectAnswers(correctCount)
}
React.useEffect(() => {
/* This function turns HTML element entities into normal words */
function decodeHtml(html) {
const txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
fetch(
"https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple"
)
.then((res) => res.json())
.then((data) => {
const dataArray = data.results;
const newDataArray = dataArray.map((item) => {
return {
question: decodeHtml(item.question),
choices: [
{
choice: decodeHtml(item.correct_answer),
isSelected: false,
correct: decodeHtml(item.correct_answer),
id: nanoid(),
},
{
choice: decodeHtml(item.incorrect_answers[0]),
isSelected: false,
correct: decodeHtml(item.correct_answer),
id: nanoid(),
},
{
choice: decodeHtml(item.incorrect_answers[1]),
isSelected: false,
correct: decodeHtml(item.correct_answer),
id: nanoid(),
},
{
choice: decodeHtml(item.incorrect_answers[2]),
isSelected: false,
correct: decodeHtml(item.correct_answer),
id: nanoid(),
},
].sort(() => 0.5 - Math.random()),
id: nanoid(),
};
});
return setQuiz(newDataArray);
});
}, []);
// console.log(quiz);
function finishQuiz() {
setEndQuiz((prevEndQuiz) => !prevEndQuiz);
}
// function startNewGame() {
// setNewGame(true);
// }
function holdAnswer(quizId, choiceId) {
setQuiz((oldQuiz) =>
oldQuiz.map((quiz) => {
if (quiz.id !== quizId) return quiz;
return {
...quiz,
choices: quiz.choices.map((choice) =>
choice.id === choiceId
? // If the choice selected is the current choice, toggle its selected state
{ ...choice, isSelected: !choice.isSelected }
: // Otherwise, deselect the choice
{ ...choice, isSelected: false }
),
};
})
);
}
const quizItemComponents = quiz.map((item) => {
return (
<QuizItem
key={item.id}
question={item.question}
choices={item.choices}
holdAnswer={(id) => holdAnswer(item.id, id)}
endQuiz={endQuiz}
correct={quiz.correct}
onSaveCorrectCountData={addCorrectCountHandler}
/>
);
});
return (
<Card className={classes.quizlist}>
{quizItemComponents}
{!endQuiz && <Button onClick={finishQuiz}>Check Answers</Button>}
{endQuiz && (
<div className={classes.result}>
<p>You scored {noOfCorrectAnswers}/5 answers</p>
<Button onClick={startNewGame}>Play Again</Button>
</div>
)}
</Card>
);
}
The error that I was getting is that there were too many re-renders, so I tried using useEffect on the setCorrectCount state within my QuizItem component (this can be seen in my code and greyed out) but it would not tally up the count.
Is there a good workaround to this problem? Any help or advice would be appreciated.
Link to the code via Stackblitz:
https://stackblitz.com/edit/quizzical
I actually have a drag and drop list from BaseWeb https://baseweb.design/components/dnd-list/,
And instead of havings strings as the exemple shows, i'm having components for a blog, like a text section, some inputs, etc... I use this list to reorder my components easily, but i got a problem, if i want to click to go in my text input, I drag my component, and don't get in.
I'm using React-Quill for the text editor
Here's my code for the list:
initialState={{
items: componentsArray
}}
onChange={({oldIndex, newIndex}) =>
setComponentsArray(newIndex === -1 ?
arrayRemove(componentsArray, oldIndex) :
arrayMove(componentsArray, oldIndex, newIndex))
}
className=""
overrides={{
DragHandle: <FontAwesomeIcon icon={Icons.faLeftRight} />,
}}
/>
Try cancel onmousedown BaseWeb's handler for elements you need to free of drag.
import React, { useState, useEffect, useRef } from 'react';
import { List, arrayMove } from 'baseui/dnd-list';
import { StatefulSelect } from 'baseui/select';
import { v4 as uuidv4 } from 'uuid';
const RulesTab = () => {
const [items, setItems] = useState([{ id: uuidv4() }, { id: uuidv4() }]);
const dndRootRef = useRef(null);
useEffect(() => {
// override base-web's mousedown event handler
dndRootRef.current.addEventListener('mousedown', (el) => {
let isFreeOfDrag = false;
let currentEl = el.target;
// check if the element you clicked is inside the "free-of-drag block"
do {
if (currentEl.getAttribute('test-id') === 'free-of-drag') {
isFreeOfDrag = true;
break;
} else {
currentEl = currentEl.parentElement;
}
} while (currentEl);
// invoke el.stopPropagation(); if the element you clicked is inside the "free-of-drag block"
if (isFreeOfDrag) {
el.stopPropagation();
}
});
}, []);
return (
<List
items={items.map(({ id }, index) => (
<div style={{ display: 'flex' }} test-id="free-of-drag" key={id}>
<StatefulSelect
options={[
{ label: 'AliceBlue', id: '#F0F8FF' },
{ label: 'AntiqueWhite', id: '#FAEBD7' },
]}
placeholder="Select color"
/>
</div>
))}
onChange={({ oldIndex, newIndex }, el) => setItems(arrayMove(items, oldIndex, newIndex))}
overrides={{
Root: {
props: {
ref: dndRootRef,
},
},
}}
/>
);
};
I was creating a react-native component when I received this error..
Failed prop type: The prop `options` is marked as required in `signupCheckBoxes`, but its value is `undefined`.
Basically, what I am doing is passing an array which contains types for the object I want to render
const inputFields = [
{
key: 'dob',
type: 'dateTyper', //change this to Dob component
label: 'Your Date of birth',
helper: 'Your Birthdate will help us in connecting you with people of similar age',
required: true
},
{
key: 'gender',
type: 'checkboxes',
label: 'Gender',
required: true,
templateOptions: {
multipleSelect: true,
options: ['Male', 'Female', 'Others']
}
]
and then mapping the component as user iterates through the array
export const SignupFormComponent = (props) => {
const {
keyboardAutoOpenForText,
inputFields,
buttonStyle,
ProgressBarProps,
backgroundViewColor,
defaultColor,
helperTextStyle,
globalButtonText,
buttonTextStyle,
textStyle,
onButtonClick,
errorStyle,
defaultErrorMessage
} = props
// All the component
const [index, setIndex] = useState(0)
const [payload, setPayloadData] = useState({})
const [Loading, toggleLoadingData] = useState(false)
const [Error, setErrorData] = useState({status: false, message: ''})
// Current Component based on indux
const currentComponent = inputFields[index]
const {key, type, label, helper, buttonText} = currentComponent
const templateOptions = currentComponent.templateOptions || {}
// if no template options, initlalize an empty object
const {number, placeHolder, templateStyle, options} = templateOptions
const usedButtonText = buttonText || globalButtonText
// Setting up/mutating props
// --- Progress bar ---
ProgressBarProps.currentProgress = index
ProgressBarProps.totalNumberOfProgressBars = inputFields.length
ProgressBarProps.colorOfProgressBar = ProgressBarProps.colorOfProgressBar || defaultColor
const onChangeHandler = (data, errorMessage=null) => {
if (!errorMessage) {
const currentData = {...payload}
currentData[key] = data
setPayloadData(currentData)
} else {
setErrorData({status: true, message: errorMessage})
}
}
const getValueFromState = async () => {
setErrorData({status: false, message: ''})
toggleLoadingData(true)
const currentValue = payload[key]
try {
const eventTrack = await onButtonClick(index, key, currentValue, payload)
if (index < inputFields.length) setIndex(index + 1)
return toggleLoadingData(false)
} catch (error) {
if (error.message) setErrorData({status: true, message: error.message})
else setErrorData({status: false, message: defaultErrorMessage})
return toggleLoadingData(false)
}
}
const mapSignUpComponents = {
text: (
<TextInput
placeholder={placeHolder}
number={number}
style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, templateStyle]}
onChangeText={text => onChangeHandler(text)}
value={payload[key] ? `${payload[key]}` : ''} // Doesn't seem right but otherwise the value of the text input also get mutate with other values
/>),
dateTyper: (
<DateTyper
textInputStyle={[{color: defaultColor, width: (Dimensions.get('window').width * 0.6)/8 }, styles.nextInputStyle, templateStyle]}
upsideEmit={onChangeHandler}/>
),
checkboxes: (
<CheckBoxes
options={options}
/>
)
}
const renderComponent = mapSignUpComponents[type]
return (
<View>
{renderComponent}
<View>
)
}
Initially, the component should be dateTyper (const renderComponent = mapSignUpComponents[type]) so the options key isn't even required, hence options are undefined
the options is a required prop for checkboxes component, but since we aren't rendering it, I am not sure why i am getting the above error
I would so appreciate if someone could help me out to solve the same.
My checkbox component looks like this
import React, {useState} from 'react'
import PropTypes from 'prop-types'
import { CheckBox } from 'react-native-elements'
import { View, Text } from 'react-native'
const signupCheckBoxes = (props) => {
const { options, multipleSelect} = props
console.log(options)
return (
<View>
<Text> Hello</Text>
</View>
)
}
signupCheckBoxes.propTypes = {
options: PropTypes.array.isRequired,
multipleSelect: PropTypes.bool
}
signupCheckBoxes.defaultProps = {
multipleSelect: true
}
export default signupCheckBoxes
It seems that you are doing <CheckBoxes options={options} /> even if options is undefined. This basically translates to initialising that component (but not calling the render function). During initialisation, react will check that all required props are available which is then throwing an error.
To fix it, I would do the following:
const mapSignUpComponents = {
text: (
<TextInput
placeholder={placeHolder}
number={number}
style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, templateStyle]}
onChangeText={text => onChangeHandler(text)}
value={payload[key] ? `${payload[key]}` : ''} // Doesn't seem right but otherwise the value of the text input also get mutate with other values
/>),
dateTyper: (
<DateTyper
textInputStyle={[{color: defaultColor, width: (Dimensions.get('window').width * 0.6)/8 }, styles.nextInputStyle, templateStyle]}
upsideEmit={onChangeHandler}/>
),
checkboxes: options === undefined ? undefined : (
<CheckBoxes
options={options}
/>
)
}
I hope this helps!
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