Selected Dropdown value is not getting populated - reactjs

I am working on Redux form. I am facing some issue with dropdown values.When I select some dropdown value, I am not getting the selected value onSubmit of the form.What could be the issue?
export class AddRecipientForm extends React.Component {
onSubmit(values) {
console.log(values)
const recipient = Object.assign({}, values);
return this.props.dispatch(addRecipient(recipient));
}
render() {
if (this.props.submitSucceeded === true) {
return (
<div>
<Redirect to={`/dashboard`} />
</div>
);
}
return (
<div>
<form
className="add-recipient-form"
aria-label="add new recipient form"
onSubmit={this.props.handleSubmit(values => this.onSubmit(values))}>
<label htmlFor="name">Name</label>
<Field component="input" name="name" type="text" />
<label htmlFor="relationship">Relationship</label>
<Field component="input" type="text" name="relationship" required />
<label htmlFor="occassion">Occassion</label>
<Field component="input" type="text" name="occassion" required />
<label htmlFor="giftDate">Gift Date</label>
<Field component="input" type="date" name="giftDate" required />
<label htmlFor="gift">Gift</label>
<Field component="input" type="text" name="gift" required />
<label htmlFor="budget">Cost</label>
<Field component="input" type="number" name="budget" required />
<label
htmlFor="status">
Gift Status
</label>
<Field component={select} name="status" required>
<option value="notPurchased">Not Purchased</option>
<option value="purchased">Purchased</option>
<option value="gifted">Gifted</option>
</Field>
<button type="submit">Submit</button>
<Link to="/dashboard">
<button type="button" aria-label="go back">
Back
</button>
</Link>
</form>
</div>
);
}
}
AddRecipientForm = reduxForm({
form: 'addRecipient'
// onSubmitFail: (errors, dispatch) => {
// console.log(`Error: ${JSON.stringify(errors)}`);
// dispatch(focus('addRecipient', Object.keys(errors)[0]));
}
)(AddRecipientForm);
export default AddRecipientForm;
I am getting other values except the dropdown values. Replaced Field with select but still its not working

Finally fixed the issue by including default dropdown value.
<option key={2333333} value={''}>Please Select</option>
But still wonder why does it require default dropdown

Related

Radio buttons with react-hook-form

I created a form with react-hook-form. It logs "fullName" and "city" correctly in the console, but not the radio buttons. With the radio buttons you get as result "null".
My code is as follows.
import React from 'react'
import './App.css';
import {useForm} from "react-hook-form";
function App() {
const {register, handleSubmit} = useForm();
function onSubmitButton(data) {
console.log(data)
}
return (
<>
<h1>Order weather</h1>
<form onSubmit={handleSubmit(onSubmitButton)}>
<input
{...register("fullName")}
type="text"
name="fullName"
placeholder="Name and surname"
id="name"
/>
<input
{...register("city")}
type="text"
name="city"
placeholder="City"
id="city"
/>
<p>I would like to:</p>
<label htmlFor="field-rain">
<input
{...register("rain")}
type="radio"
name="weather"
value="rain"
id="field-rain"
/>
Rain
</label>
<label htmlFor="field-wind">
<input
{...register("wind")}
type="radio"
name="weather"
value="wind"
id="field-wind"
/>
Lots of wind
</label>
<label htmlFor="field-sun">
<input
{...register("sun")}
type="radio"
name="weather"
value="sun"
id="field-sun"
/>
Sunny
</label>
<button type="submit">
Send
</button>
</form>
</>
);
}
export default App;
When I turn off name= "weather" and I check the buttons it does put it in the console, but it is not supposed to allow me to check all the buttons at the same time. Anyone have an idea how I can make sure I can get what is checked into the console?
Since rain, wind, sun should be assign to the same value we need to pass same params to register function as below
function App() {
const {register, handleSubmit} = useForm();
function onSubmitButton(data) {
console.log(data)
}
return (
<>
<h1>Order weather</h1>
<form onSubmit={handleSubmit(onSubmitButton)}>
<input
{...register("fullName")}
type="text"
placeholder="Name and surname"
id="name"
/>
<input
{...register("city")}
type="text"
placeholder="City"
id="city"
/>
<p>I would like to:</p>
<label htmlFor="field-rain">
<input
{...register("weather")}
type="radio"
value="rain"
id="field-rain"
/>
Rain
</label>
<label htmlFor="field-wind">
<input
{...register("weather")}
type="radio"
value="wind"
id="field-wind"
/>
Lots of wind
</label>
<label htmlFor="field-sun">
<input
{...register("weather")}
type="radio"
value="sun"
id="field-sun"
/>
Sunny
</label>
<button type="submit">
Send
</button>
</form>
</>
);
}
export default App;
I hope this will fix the issue.

Changing state on route change in React

I want to show a select tag when a checkbox is checked.
In "/register" route (which is the default route), checkbox should be unchecked by default and in "/register/tradeUser", checkbox should be checked by default.
If I use defaultChecked="true", the state of checked will not change to true.
So I want to know, how can I call setChecked(true) inside the conditional rendering?
const Register = (match) => {
const [checked, setChecked] = useState(false);
const toggleChecked = () => {
if (checked) {
setChecked(false);
} else {
setChecked(true);
}
};
return (
<form>
<input type="text" name="first-name" placeholder="First Name" />
<input type="text" name="last-name" placeholder="Last Name" />
<input type="email" name="email" placeholder="Email Address" />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="confirm" placeholder="Confirm Password" />
{match.location.pathname === "/register/tradeUser" ? (
<div>
<label>
<input
type="checkbox"
name="profession"
checked={checked}
onChange={() => toggleChecked()}
/>
I am an Architect/Interior designer
</label>
<select
name="info"
placeholder="Select Option to add Architect Info"
className={`${checked ? "" : "hidden"}`}
>
<option value="certi-number">Certificate Number</option>
<option value="certificate">Registration Certificate</option>
</select>
</div>
) : (
<div>
<label>
<input
type="checkbox"
name="profession"
checked={checked}
onChange={() => toggleChecked()}
/>
I am an Architect/Interior designer
</label>
<select
name="info"
placeholder="Select Option to add Architect Info"
className={`${checked ? "" : "hidden"}`}
>
<option value="certi-number">Certificate Number</option>
<option value="certificate">Registration Certificate</option>
</select>
</div>
)}
<button>Register</button>
</form>
<label>
Existing User?
<Link to="/login" className="link">
{" Login "}
</Link>
</label>
</div>
);
};
you can easily run function in jsx like this
export default function App() {
return (
<div className="App">
{console.log(1)}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
however you shouldn't set state in jsx because it will loop infinitely
in this case you can use useEffect
useEffect(()=>{
if(match.location.pathname=== "/register/tradeUser"){
setChecked(true)
}else{
setChecked(false)
}
},[match.location.pathname])

Redux form, clear and rest for one specific field, react JS

how would I specify in clear button, that i only need to reset the dropdown field and not everything else
import React from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm, formValueSelector } from 'redux-form'
let SelectingFormValuesForm = (props) => {
const {
favoriteColorValue, fullName, handleSubmit, hasEmailValue, pristine, reset, submitting
} = props
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field name="firstName" component="input" type="text" placeholder="First Name"/>
</div>
</div>
<div>
<label>Last Name</label>
<div>
<Field name="lastName" component="input" type="text" placeholder="Last Name"/>
</div>
</div>
<div>
<label htmlFor="hasEmail">Has Email?</label>
<div>
<Field name="hasEmail" id="hasEmail" component="input" type="checkbox"/>
</div>
</div>
{hasEmailValue && <div>
<label>Email</label>
<div>
<Field name="email" component="input" type="email" placeholder="Email"/>
</div>
</div>}
<div>
<label>Favorite Color</label>
<div>
<Field name="favoriteColor" component="select">
<option></option>
<option value="#ff0000">Red</option>
<option value="#00ff00">Green</option>
<option value="#0000ff">Blue</option>
</Field>
</div>
</div>
{favoriteColorValue && <div style={{
height: 80,
width: 200,
margin: '10px auto',
backgroundColor: favoriteColorValue
}}/>}
<div>
<button type="submit" disabled={pristine || submitting}>Submit {fullName}</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values
</button>
</div>
</form>
)
}
https://redux-form.com/6.0.2/examples/selectingformvalues/
If you use refux-form version 6.0.2 You can update it to the latest and use clearFields (doc)
clearFields(form:String, keepTouched: boolean, persistentSubmitErrors: boolean, ...fields:String)
Cleans fields values for all the fields passed in. Will reset to initialValue for each field if has any.
If the keepTouched parameter is true, the values of currently touched fields will be retained.
If the persistentSubmitErrors parameter is true, the values of currently submit errors fields will be retained
dispatch(clearFields('FORM_NAME', false, false, 'favoriteColor'));

Redux Form Validation error while using field names like user.name

I have a react component with a redux form as below
<div className="col-sm-12">
<div className="form-group row">
<div className="col-sm-4">
<label>A. Name</label>
</div>
<div className="col-sm-8">
<ul className="sub-qn-ans-list d-flex list-unstyled">
<li>
<Field
name="first_name"
component={renderField}
type="text"
placeholder="First name"
className="form-control" />
</li>
<li>
<Field
name="last_name"
component={renderField}
placeholder="Last name"
type="text"
className="form-control" />
</li>
</ul>
</div>
</div>
<div className="form-group row">
<div className="col-sm-4">
<label>B. Residential Address</label>
</div>
<div className="col-sm-8">
<ul className="sub-qn-ans-list d-flex list-unstyled">
<li>
<Field
name="residential.street"
component={renderField}
placeholder="Street"
type="text"
className="form-control" />
</li>
<li>
<Field
name="residential.area"
component={renderField}
placeholder="Area"
type="text"
className="form-control" />
</li>
<li>
<Field
name="residential.city"
component={renderField}
placeholder="City"
type="text"
className="form-control" />
</li>
<li>
<Field
name="residential.district"
component={renderField}
placeholder="District"
type="text"
className="form-control" />
</li>
<li>
<Field
name="residential.landline"
component={renderField}
placeholder="Landline"
type="text"
className="form-control" />
</li>
<li>
<Field
name="residential.mobile"
component={renderField}
placeholder="Mobile"
type="text"
className="form-control" />
</li>
</ul>
</div>
</div>
</div>
I'm trying to apply validations for the input fields. The validation for the fields first_name and last_name works fine. But I get an error when I'm trying to apply validation for residential.street.
Below is my code for the validation.
const LocatorValidation = (values, form) => {
const errors = {};
if (!values.first_name) {
errors.first_name = 'Required';
} else if (!/[A-Za-z.]+/.test(values.first_name)) {
errors.first_name = 'First name must have only alphabets';
}
if (!values.last_name) {
errors.last_name = 'Required';
} else if (!/^[A-Za-z.]+$/.test(values.last_name)) {
errors.last_name = 'First name must have only alphabets';
}
if (!values.residential) {
errors.residential.street = 'Required';
}
return errors;
}
export default LocatorValidation;
Here is the image which shows the error.
As the error states in errors.residential.street the residential property of errors is undefined. So you need to set it as empty object first like
errors.residential = {}
errors.residential.street = "Required"
I would also improve the check
!values.residential || !values.residential.street

How to redirect after summit form

because react-router v4 can't use 'browserHistory' then what should i do? if i want go to next page after summit form. here is my code
let Profile = ({ history, handleSubmit }) => {
return (
<FirstSec>
<div>
<p>Profile</p>
<form onSubmit={handleSubmit(submit)} >
<div className="form-group">
<Field name="firstName" type="text" className="form-control" label="first name" component={renderField} />
<Field name="lastName" type="text" className="form-control" label="last name" component={renderField} />
<Field name="tel" type="tel" className="form-control" label="tel" component={renderField} />
<Field name="email" type="email" className="form-control" label="email" component={renderField} />
</div>
<button onClick={() => history.push('/apply/1/Occupation')}>Back</button>
<button type="submit">Next</button>
</form>
</div>
</FirstSec>
);
};
Profile = reduxForm({
form: 'profile'
})(Profile);
You should use React-redux-router for it.

Resources