Yup with Formik doesn't Datepicker value - javascript

I have been trying everything to make this form work with yup, but when using the date-picker, the value doesn't register either within the field or with yup.
My relevant imports are formik, yup, useForm and yupResolver.
I have removed non-relevant code to save space. The other fields i have are first name, last name, email and phone number, and they all work as they should, with values registering and errors showing up when they don't fill the criteria.
I have a console log withing the formik element which logs all the values, and all the values get logged properly except the dates, which stand empty.
const Form = () => {
const [fromDate, setFromDate] = useState(new Date());
return (
<>
<div>
<Formik validationSchema={formVal}>
{({ values,
errors) => (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<DatePicker
id="fromDate"
onChange={(date) => {
setFieldValue(date);
}}
/>
</div>
<Button type="submit" ></Button>
</form>
)}
</Formik>
</div>
</>
)}

It seems like you're not using 'setFieldValue' correctly;
The 1st argument should be the form's field name.
Should be something like this: setFieldValue('fromDate', date);
See https://formik.org/docs/api/formik for reference.
Also, make sure that variable 'date' is of type Date and not an object, containing the actual date value.

Related

autocomplete is off but input field adding value automatically[ReactJs]

We have a ReactJs web application and we are taking some data through of input field but the problem is sometimes this field fills data automatically
For more specification, this problem happens when we are using Oppo and Redmi(OS) but for other OS it's working as normal
For more clear understanding, we made a video using Redmi mobile phone, and here is the video link, Please have a look at the video from the link.
https://drive.google.com/file/d/1yo03CjqeV9iFXgtSH-ff7zgH1hJq60BY/view?usp=sharing
Here is the input field code
// Formik Field
<Field name={name}>
{({ field }: any) => {
return (
<input
{...rest}
{...field}
id={name}
type="text"
autoComplete="off" // we use before off= boolean
value={values.data}
placeholder="Input data"
className={`appoint-input-box ${errors && touched ? " error-red-400" : null}`}
onChange={async (event) => {
handleFiend(event);
setFieldValue("data", event.value.toLowerCase());
}}
/>
);
}}
</Field>
As we said before, this is a ReactJs web app but for form handling we use Formik and this is a text-type input field also this form is a child form, it has a parent form as a controller.
Now we have autoComplete="off" but before we use boolean and top label form we also use the same.
We are hoping, that the provided information is describing properly the exact issue.
If someone expert can guide us on what to do then it's will really pleasure
Thanks
Internazionaleauto

How can I submit my textbox value to go to a a link in React js?

I am trying to create a video conference, what I need is to join the room by entering a link to the textbox.
Right now, I have able to get the textbox value but the problem is I cannot go to another link. Can anyone help me with this?
function Home(){
const [data,setData] = useState(null)
const [print, setPrint] = useState(false);
function getData(val){
setData(val.target.value)
setPrint(false)
}
return(
<React.Fragment>
<h3>Welcome, Instructor</h3>
<hr />
{
print?
<h1>{data}</h1>
:null
}
{/* Link supposed to be here */}
<TextField label="Room ID" onChange={getData} />
<hr/>
<Button variant="contained" color="primary" onClick={() => setPrint(true)}>JOIN ROOM</Button>
</React.Fragment>
)
}
export default Home;
You can use Link in react-router-dom
<Link to={`/${data}`}>Join</Link>
<TextField label="Room ID" onChange={getData} />
What you specifically need, is using the textbox information, you want to generate dynamic links.
In such a case, we can be certain that, we need to use the dynamic information to create the link, which can be achieved either by concatenation
const name = "Mike";
console.log("Hello" + name); // Hello Mike
or you can use string interpolation / templating
const name = "Mike";
console.log(`Hello` ${name}`); // Hello Mike
Both of these are Javascript features and have nothing to do with React specifically.
The React specific information here is, whenever variables inside JSX part of components change, re-renders are caused and thus links will be updated.
So, anything like <a href=`https://example.com/some/random/${stateVariable}/chat` />

react this.setState isn't updated state

I'm trying to figure out why a call to this.setState isn't updating state.
I have the following lines method:
changeState(state, value){
this.setState({state:value}, ()=>console.log(this.state));
}
There are a few function using this, but one is a file upload component. Its a simple component that either renders a file input OR it renders an iframe, disabled input, and button. When the button is clicked I want to change the state in the parent component which then rerenders the file component and shows a file picker.
The call to this.setState seems to work ok, but when I console log state after it runs or if I stop execution before the next render takes place state is unaffected. My file upload component has a method like this:
renderField(field){
if(this.props.hasOwnProperty('file') && this.props.file){
return(
<div>
<iframe src={this.props.file} frameborder="0"> </iframe>
<input
disabled
placeholder={this.props.file}
name={field.name}
type='text'
/>
<span onClick={()=>this.props.changeFile(this.props.file_type, null)}>× Remove</span>
</div>
)
}else{
return(
<input
{...field}
type={field.type}
name={field.name}
onChange={(event) =>{
field.input.onChange(field.input.value = event.target.files[0])}
}
/>
)
}
}
when I call the method I get this output:
however after console logging my state is anything but changed:
You don't want to set the state property in your state, but the property name that state contains.
You can use a computed property name for this.
changeState(state, value) {
this.setState({ [state]: value }, () => console.log(this.state));
}

React form's defaultValue updates on page reload when a unique key is assigned to it but it doesn't when key is not there

I am currently working on edit functionality using react form and want the data in the form fields to be pre-populated with the props value and for that I have assigned it to defaultValue in the form fields.
But the problem I came across while doing this is my defaultValues flush out on page reload. I tried finding a solution for it and came across few hacks to make the dom in sync with defaultValue. One of which was assigning a key to the wrapper component of the input field.
What is the reason for this behaviour of defaultValue?
Could anyone please help me figure out why the form field behaves like that? Here's the related snippet:
var title = this.props.post.title;
return (
<form
onSubmit={
postId ? this.handleUpdate.bind(this) :
this.handleSubmit.bind(this)
}
>
<h3>
{postId ? "Edit post" : "Create a New Post"}
</h3>
<FormGroup key={title} controlId="formControlsText">
<ControlLabel>Title</ControlLabel>
<FormControl
type="text"
inputRef={ref => {
this.title = ref;
}}
placeholder="Enter title"
defaultValue={title}
/>
</FormGroup>
</form>
)

ReactJS error warning

I'm creating my first application with ReactJS and I found this warning when I run my code :
Warning: Failed form propType: You provided a checked prop to a form
field without an onChange handler. This will render a read-only
field. If the field should be mutable use defaultChecked. Otherwise,
set either onChange or readOnly. Check the render method of
Login.
Can someone tell me how I fix it please ?
React has 2 ways of working with form controls - Controlled Components and Uncontrolled Components
You get this warning when you don't supply the element neither the attributes needed for controlled nor those needed for an uncontrolled component:
Warning: Failed form propType: You provided a checked prop to a form
field without an onChange handler. This will render a read-only field.
If the field should be mutable use defaultChecked. Otherwise, set
either onChange or readOnly. Check the render method of Login.
Controlled Components
Attributes needed:
value - <input> (not checkbox or radio), <select>, <textbox> or checked for (checkbox or radio).
onChange
React handles the condition of the element by updating the value or checked attribute (depending on the element) from the props or the state. We need to notify react when we make a change, like inserting data, or checking the box, so react can update the element's condition when it rerenders the component. To do so, we must include an onChange handler, in which we will update the state or notify the component's parent, so it will update the props.
<input
type="checkbox"
checked={ this.props.checked }
onChange={ this.checkboxHandler }
/>
const { render } = ReactDOM;
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: true
};
this.checkboxHandler = this.checkboxHandler.bind(this);
}
checkboxHandler(e) {
this.setState({
checked: e.target.checked
});
}
render() {
return (
<input
type="checkbox"
checked={ this.state.checked }
onChange={ this.checkboxHandler }
/>
);
}
}
render(
<Demo />,
document.getElementById('demo')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>
<h1>The Checkbox</h1>
<div id="demo"></div>
Uncontrolled Components
Attributes needed:
defaultValue - <input> (not checkbox or radio), <select>, <textbox> or defaultChecked for (checkbox or radio).
React sets the initial value using defaultValue or defaultChecked, and the update of the element's state is controlled by the user, usually via the DOM using refs.
<input
type="checkbox"
defaultChecked={ this.props.checked }
/>
The defaultChecked may not be updated if the component is re-rendered in future so use this approach with caution.
You may be better off just using a blank function to remove the warning. Especially if you want to handle click on the whole div which includes the checkbox and the associated text.
<div onClick={this.handleClick}>
<input type="checkbox" checked={this.props.checked} onChange={()=>{}}/>
{this.props.text}
</div>
You need to add defaultChecked attribute to your checkbox:
<div>
<input type='checkbox' defaultChecked />
</div>
For those that prefer a Functional Component instead of a Class Component this Controlled Component approach is simple and easy to implement. If you don't know what a Controlled Component is then please refer to #Ori Drori's well explained answer in this thread.
import {useState} from "react";
export default function YourComponentName(){
const [checked, setChecked] = useState(true);
return (
<>
<input
type="checkbox"
checked={checked}
onChange={() => setChecked(!checked)}
/>
</>
);
};
If your confronting with this warning, You can add "readOnly" to your input. like this code:
<div>
<input type='checkbox' checked={ props.checkBoxChecked } readOnly />
</div>
Or You can add an onChange event like an empty arrow function or what kind of function you care about to your input. like this:
<div>
<input type='checkbox' checked={ props.checkBoxChecked } onChange={() => {}} />
</div>
Also you must care about the value property, too.
This solution fixed my issue with the same warning, hope to be useful.

Categories

Resources