Does conditional fields with radio buttons in react forms work? - javascript

I am creating a form with 'occupation' field as radio button. There are two options for occupation-i.e. self employed and service. According to the choice the user makes for occupation, I am showing different fields of the form. I am using if-else for this conditional rendering. Code works well for if-part but doesn't work for the else-part. I am attaching my code for reference.
<div className="row">
<div className="col-md-3">
<input
type= "radio"
id= "fatherService"
name= "fatherOccupation"
value = "service"
checked={fatherOccupation === "service"}
onChange={handleFatherOccupation}
/>
<label htmlFor="fatherService">Service</label>
</div>
<div className="col-md-6">
<input
type= "radio"
id= "fatherSelfEmployed"
name= "fatherOccupation"
value = "selfEmployed"
checked={fatherOccupation === "selfEmployed"}
onChange={handleFatherOccupation}
/>
<label htmlFor="fatherSelfEmployed">Self Employed</label>
</div>
</div>
</div>
</div>
{fatherOccupation === "service" ? (
<div className="row">
<div className="col-md-6">
<label>Company Name:</label>
<input
type="text"
className="form-control p-2"
id="fatherCompanyName"
name="fatherCompanyName"
{...register("fatherCompanyName", {
required:"Please enter father's company name",
})}
/>
</div>
</div>
) : (
<div className="row">
<div className="col-md-6">
<label>Type of Business:</label>
<input
type="text"
className="form-control p-2"
id="fatherTypeOfBusiness"
name="fatherTypeOfBusiness"
{...register("fatherTypeOfBusiness", {
required:"Please enter father's type of business",
})}
/>
</div>
</div>
)}

Related

React needs to be handled some if conditions

I have an issue with the if statement. The problem is I need to create a condition if the array has 2 object needs to be true if has 1 object it should be false. the objects are strings please check the code.
const { program } = useContext(ProgramContext);
const { authMethods } = program;
let loginComponent;
let claimComponent;
let insertRow;
let insertEnd;
if (authMethods) {
if (authMethods.indexOf('login') !== -1) {
loginComponent = (
<div className="col-md-6 d-flex">
<div className="card flex-grow-1 mb-md-0">
<div className="card-body">
<h3 className="card-title">Login</h3>
<form>
<div className="form-group">
<label htmlFor="login-id">User ID</label>
<input
id="login-id"
className="form-control"
placeholder="Please enter user ID"
/>
</div>
<div className="form-group">
<label htmlFor="login-password">Password</label>
<input
id="login-password"
type="password"
className="form-control"
placeholder="Password"
/>
<small className="form-text text-muted">
<ErrModal />
</small>
</div>
<div className="form-group">
<div className="form-check">
<span className="form-check-input input-check">
<span className="input-check__body">
<input
id="login-remember"
type="checkbox"
className="input-check__input"
/>
<span className="input-check__box" />
<Check9x7Svg className="input-check__icon" />
</span>
</span>
<label className="form-check-label" htmlFor="login-remember">
Remember Me
</label>
</div>
</div>
<button type="submit" className="btn btn-primary mt-2 mt-md-3 mt-lg-4">
Login
</button>
</form>
</div>
</div>
</div>
);
}
if (authMethods.indexOf('claim') !== -1) {
claimComponent = (
<div className="col-md-6 d-flex mt-4 mt-md-0">
<div className="card flex-grow-1 mb-0">
<div className="card-body">
<h3 className="card-title">Claim</h3>
<form>
<div className="form-group">
<label htmlFor="claim-code">Enter Claim Code</label>
<input
id="register-email"
type="text"
className="form-control"
placeholder="Claim Code"
/>
</div>
<button type="submit" className="btn btn-primary" style={{ marginTop: '186px' }}>
Claim
</button>
</form>
</div>
</div>
</div>
);
}
}
console.log(loginComponent);
console.log(claimComponent);
const rowComponent = (
<div className="container">
{insertRow}
{loginComponent}
{claimComponent}
{insertEnd}
</div>
);
Basically I want to add row class if there are 2 items in the array otherwise I don't need a row.
thank you
Your question is not clear so I'll chalk out a similar example:
import React from 'react'
const Component = () => {
const arr = ["foo", "bar"];
const rowClass = arr.length === 2 ? "row" : "";
return (
<div className={rowClass}>
This is an example
</div>
)
}
export default Component

One input component but different states for each occurrence

I have created a component element. I am using it in a form.
I put the state in the class for the input component and when i do console log and they all seem to share the same state? is this normal. will need to post the values into laravel api and store to mysql next. is the following correct or do i need to create an input component for each field i require. Eg. one for name, one for surname one for telephone one for email etc:
import React from 'react';
import styles from './Input.module.scss';
export class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(e) {
this.setState({ inputValue: e.target.value });
}
render() {
console.log(this.state.inputValue)
return (
<div className={styles.container}>
<label htmlFor={this.props.id} className={styles.label} > {this.props.label} </label>
<input
id={this.props.id}
className={styles.input}
type="text"
value={this.state.inputValue}
onChange={this.onInputChange}
/>
</div>
);
}
};
reusing same component here:
render() {
return (
<div className={styles.contactForm} >
<form onSubmit={this.onFormSubmit}>
<div className={styles.contactBlock} >
<div className={styles.header} onClick={this.onStepOneClick} >
<BoxHeader title="Step 1: Your Details" />
</div>
<div className={styles[this.state.stepOne]}>
<div>
<Input type="text" label="First Name" id="name" />
<Input type="text" label="Surname" id="surname" />
</div>
<div>
<Input type="email" label="Email Address" id="email" />
</div>
<div className={styles.button} onClick={this.onStepOneClick}>
<Button innerHTML="Next >" />
</div>
</div>
</div>
<div className={styles.contactBlock} >
<div className={styles.header} onClick={this.onStepTwoClick} >
<BoxHeader title="Step 2: More Comments" />
</div>
<div className={styles[this.state.stepTwo]}>
<div>
<Input type="tel" label="Telephone Number" id="tel" />
<Select label="Gender" id="gender" >
<option> Male </option>
<option> Female </option>
<option> Other </option>
</Select>
</div>
<div>
<Date label="Date of Birth" id="dob"/>
</div>
<div className={styles.button} onClick={this.onStepTwoClick}>
<Button innerHTML="Next >" />
</div>
</div>
</div>
<div className={styles.contactBlock} >
<div className={styles.header} onClick={this.onStepThreeClick} >
<BoxHeader title="Step 3: Final Comments" />
</div>
<div className={styles[this.state.stepThree]}>
<div className={styles.textArea}>
<Textarea label="Comments" id="comment" />
</div>
<div className={styles.submit}>
<Submit innerHTML="Next >" />
</div>
</div>
</div>
</form>
</div>
);
Yes, for each field you would need to create a new input. This can be within same or new component whichever you prefer.

OnChange function of input type radio in reactjs?

I am having input tags with radio type
<div className="col-md-12">
<div className="form-group clearfix">
<label htmlFor="" className="col-md-2 control-label">Authentication</label>
<div className="col-md-8">
<input type="radio" name="authentication" value="No Authentication" onChange={this.Authentication.bind(this)} />
No Authentication
<input type="radio" name="authentication" value="Master Credentials" onChange={this.Authentication.bind(this)} />
Master Credentials
</div>
</div>
</div>
And the onChange function
Authentication(e) {
this.setState({ authentication: e.target.value });
}
onChange is getting called only for the first time when i click on second time onChange is not getting called not able to identify what is the problem.
Add checked props like below:
<div className="col-md-12">
<div className="form-group clearfix">
<label htmlFor="" className="col-md-2 control-label">
Authentication
</label>
<div className="col-md-8">
<input
type="radio"
name="authentication"
value="No Authentication"
checked={this.state.authentication === "No Authentication"}
onChange={this.Authentication.bind(this)}
/>
No Authentication
<input
type="radio"
name="authentication"
value="Master Credentials"
onChange={this.Authentication.bind(this)}
checked={this.state.authentication === "Master Credentials"}
/>
Master Credentials
</div>
</div>
</div>;
Demo code.

How to display maxlength of input as user starts typing?

The input field of my website looks like this:(click here to view image)
It's code in jsx file looks like this:
render: function () {
return (
<form id="addcourse" role="form" className="form-horizontal" enctype="multipart/form-data" ref="courseForm">
<fieldset>
<CategoryLoader callback={this.handleCategoryChange}/>
<div className="form-group">
<label className="control-label col-md-2 col-md-offset-1">Title</label>
<div className="col-md-7 col-md-offset-1">
<input name="title" type="text" maxLength="6" id="abcd" className="form-control" ref="title" placeholder="Title (Maximum 100 characters)"/>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-2 col-md-offset-1">Course Image</label>
<div className="col-md-7 col-md-offset-1">
<input name="image" type="file" className="form-control" ref="image"/>
<p className="help-block">Upload image for the course </p>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-2 col-md-offset-1">Enrollment Type</label>
<div className="col-md-7 col-md-offset-1">
<select ref="enrollment_type" name="enrollment_type" className="form-control">
<option value="O">Open</option>
<option value="M">Moderated</option>
</select>
</div>
</div>
<div className="form-group">
<div className="col-md-2 col-md-offset-2 addcoursebutton">
<button ref="submit" className="btn btn-primary" type="button" onClick={this.add_course}>Add
Course
</button>
</div>
<div className="col-md-1">
<button type="button" onClick={this.props.closeCallBack} className="btn btn-danger">
Close
</button>
</div>
</div>
</fieldset>
</form>
);
I've tried maxLength="6".
It won't take more than 6 characters in input but it doesn't give any error like "Maximum length is 6 characters."
So, when the user starts typing in that field, I want it to display a message under input field,"Maximum of 6 characters are allowed".
How can I do that?
try this :
$(elementId).onchange(function(){
var len = this.val.length;
if (len > 5)
alert("You cannot exceed max of 6 characters").
});
you can also use 'onkeypress' event as well and any other type of result than alert, whatever suits
This is quite simple and react way of doing this is using state.
if you need more explanation let me know. hope this will help.
checkMaxLen = e => {
if (e.target.value.length > 6) {
this.setState({ errorText: "Length cant exceed more then 6" });
} else {
if (this.errorText) {
this.setState({ errorText: "" });
}
}
};
<input type="text"
onChange={this.checkMaxLen}
/>
{this.state.errorText && <span>{this.state.errorText}</span>}
You can even achieve it with CSS only. Here is the explanation

input doesnt display value

I have this code:
<input type="text" id="secound-kreab" placeholder="Twitter name" name="WebsitesAndSocial[]" value="europarl.com">
Rendered by:
{this.state.Contact.WebsitesAndSocial.map((WebSocial, Index) => {
return (
<div className="row">
<div className="col s12 m4 l4">
<label htmlFor=""><i className="material-icons">language</i> Websites & Other Links: </label>
<input id="secound-kreab" type="text" placeholder="Twitter name" name="WebsitesAndSocial[]" defaultValue={WebSocial} />
</div>
{Index == 0 ?
<div id="add-web" className="add-web btn-floating kreab-color" onClick={this.addWeb} >
<i className="material-icons">add</i>
</div>
: null}
</div>
)
})}
But the browser dosn't display de "value" prop of the tag.
dosnt render the value prop

Categories

Resources