DatePicker not getting disabled on change in state - reactjs

Please see the following code. I have a dropdown with 3 values, the DatePicker should conditionally get disabled when the user chooses 1, or 2 from the dropdown. But this is not happening.
import React, { useState } from 'react';
import ReactDatePicker from "react-datepicker";
export default function DateRangePicker() {
const [startDate, setStartDate] = useState("");
const [rangeType, setRangeType] = useState(1);
return <div>
<select value={rangeType} onChange={e => setRangeType(e.target.value)}>
<option value="1">This Month</option>
<option value="2">This Year</option>
<option value="3">Date Range</option>
</select>
<br />
<ReactDatePicker
disabled={rangeType !== 3}
selected={startDate}
onChange={e => setStartDate(e)}
/>
</div>;
}
What am I doing wrong here?
Thanks

Print a console log on the onChange, but from what I'm reading I suppose that the problem is the type: you're comparing string and numbers.

Related

anyone help me with this in react , old values are again console logging with the present value selected value

when i tried to store status value in the values state and then try to access it but it is showing previous values with the present value
and i got an error like this
Error: Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
at input
at div
at App (https://aid-
`
import React, { useState , useEffect } from "react";
import "./App.css";
function App() {
//values
const [values, setValues] = useState({
title: "",
owner: "",
status: "",
effort: "",
due: ""
})
//seting values
const settingValues=(e)=>{
setValues({[e.target.name]:e.target.value})
}
useEffect(()=>{
console.log(values.status)
},values)
const style = { display:"flex",flexDirection:"column",padding: "5px",margin:"2px" }
return (
<div className="App" style={style}>
<input type="text" name="title" value={values.title} onChange={(e)=>settingValues(e)} placeholder="title" style={style} />
<input type="text" name="owner" value={values.owner} onChange={(e)=>settingValues(e)} placeholder="owner" style={style} />
<select name="status" value={values.status} onChange={(e)=>settingValues(e)} style={style}>
<option value="Status">status</option>
<option value="New">New</option>
<option value="Assaigned">Assaigned</option>
<option value="Fixed">Fixed</option>
<option value="Closed">Closed</option>
</select>
<input type="number" name="effort" value={values.effort} onChange={(e)=>settingValues(e)} placeholder="effort" style={style} />
<input type="date" name="due" value={values.due} onChange={(e)=>settingValues(e)} style={style} />
</div>
);
}
export default App;
`
UseEffect is expecting a dependancy array as a second parameter, but it looks like you're giving it an object from state.
useEffect(()=>{
console.log(values.status)
},[values])
Also, checkout this post. I found it helpful when using useEffect

React - Ant Design Form-Item name props broke Select value

I m using antD and if I use select component inside of form item and if this form item has name as props I can not set value to my select component while page was rendering.
Just make it clear what I tried to say, I prepared a example and you can copy and paste it to the codesandbox or etc.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Select } from 'antd';
const { Option } = Select;
export const Demo =()=> {
let formRef = React.createRef();
return (
<Form ref={formRef} name="control-ref">
<Form.Item
label="Gender"
rules={[
{
required: true,
},
]}
>
<Select value="male">
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
</Form>
);
}
ReactDOM.render(<Demo />, document.getElementById('container'));
If you try to give name props to form item in this example your select component's initial value will not
be set.
More over using hooks not solved my problem.
I do not fully understand your question, but as far as I do, I'll try to help.
You can try useRef.
import React,{useRef, useEffect} from 'react';
export const Demo =()=> {
var formRef = useRef();
useEffect(() => {
formRef.current.setFieldsValue({
select:"male"
})
});
<Form ref={formRef} name="control-ref">
<Form.Item
label="Gender"
name="select"
rules={[
{
required: true,
},
]}
>
<Select>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
</Form>
);}
Do not forget to give the name of the relevant Form.Item.

Is it possible to get react-hook-form defaultValue updating with state?

I would like to auto-fill a text field based on the selection made in a dropdown, I thought that the state change would cause the form to re-render and thus create the desired effect, however this is not the case.
Here is the minimum working example that demonstrates my problem.
import React from 'react';
import { useForm } from 'react-hook-form';
function FormTest (){
const [dropdownValue, setDropdownValue] = React.useState('Option 1');
const { register, handleSubmit } = useForm({
defaultValues: {
textfield: dropdownValue,
},
mode: 'onChange'
},);
const onSubmit = (form) => {
alert(JSON.stringify(form))
}
return(
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<select name='dropdown'
ref={register}
value={dropdownValue}
onChange={(e) => setDropdownValue(e.currentTarget.value)}>
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
</select>
<input type='text'
name="textfield"
ref={register}
/>
<input type='submit'/>
</form>
</div>
);
}
export default FormTest;
When I change the dropdown from Option 1 to Option 2, dropdownValue is changed to Option 2 however, the text in the text field remains as Option 1. Is there a way to get this updating? Perhaps a forced re-render of the text field? Or is this not possible?
Thanks
You can use setValue from "react-hook-form":
const { register, handleSubmit, setValue } = useForm({ // setValue
// ...
})
setValue will accept the name and the new value:
onChange={(e) => {
setDropdownValue(e.currentTarget.value)
setValue('textfield', e.currentTarget.value)
}}

How to clear <Input type="select"> selected value in Reactstrap?

I have a <select> object in Reactstrap, created by means of Reactstrap's <Input> component. I want to programmatically deselect a selected object within it, so I am using state to control the value of the <select> and setting the state to be '' (an empty string) when I want to clear the state. However, this is having the effect of setting the first item in the select object to be selected, not deselecting it.
import React, { useState } from 'react';
import "./styles.css";
import {Input, Button} from 'reactstrap';
export default function App() {
const [selectedOption, setSelectedOption] = useState<string>('');
const onChangeSelection = (e: any) => {
setSelectedOption(e.target.value);
}
const clearSelection = () => {
setSelectedOption('');
}
return (
<div className="App">
<div>
<Input type={"select"} size='2' value={selectedOption} onChange={onChangeSelection}>
<option value={"option1"}>Option 1</option>
<option value={"option2"}>Option 2</option>
</Input>
</div>
<div>
<Button onClick={clearSelection}>Clear selection</Button>
</div>
</div>
);
}
There is an example of the problem
How do I deselect any selected items?
Add hidden option with value of empty string.
import React, { useState } from "react";
import "./styles.css";
import { Input, Button } from "reactstrap";
export default function App() {
const [selectedOption, setSelectedOption] = useState<string>("");
const onChangeSelection = (e: any) => {
setSelectedOption(e.target.value);
};
const clearSelection = () => {
setSelectedOption("hidden");
};
return (
<div className="App">
<div>
<Input
type={"select"}
size="2"
value={selectedOption}
onChange={onChangeSelection}
>
<option value="" hidden></option>
<option value={"option1"}>Option 1</option>
<option value={"option2"}>Option 2</option>
</Input>
</div>
<p>
Clicking the clear button selects option 1, instead of deselecting any
selected item.
</p>
<div>
<Button onClick={clearSelection}>Clear selection</Button>
</div>
</div>
);
}

Firebase - set default value in select field after form submit

I have simple form with dropdown select menu. How do I reset the select field back to show first option after submission ( ---Select category---)? I have tried setCategory("") or setCategory("---Select category---") but it keeps showing category i have picked.
const [category, setCategory] = useState("");
function formSubmit(e) {
e.preventDefault();
firebase
.firestore()
.collection("posts")
.add({
category,
})
.then(() => {
setCategory("");
});
}
<form onSubmit={formSubmit}>
<div>
<label htmlFor="category">Post Category</label>
<select
name="category"
onChange={(e) => setCategory(e.currentTarget.value)}
>
<option value="">--- Select category ---</option>
<option value="react">React</option>
<option value="CSS">CSS</option>
<option value="misc">Misc</option>
</select>
<div>
<button type="submit">Add</button>
</div>
</div>
After doing a little bit of research I found this questions answered here, here, and here. However, I would advice you to use the react-advanced-form library which makes this task a lot easier and will give you more features to implement on your forms.
While using this library you want to use “form.reset()” on your action button. This will let you set initial values for each field and the action will set the values of your fields to this default value. Here is an example:
import React from 'react'
import { Form } from 'react-advanced-form'
import { Input } from 'react-advanced-form-addons'
export default class Example extends React.Component {
handleSubmitted = ({ res, fields, form }) => {
form.reset() // resets "username" field to "admin"
}
render() {
return (
<Form onSubmitted={this.handleSubmitted}>
<Input
name="username"
initialValue="admin" />
</Form>
)
}
}

Resources