Show or hide on multiple element using class in React - reactjs

I am using the class component here Consider selecting Yes or No value depending on whether to show or hide the div.
I wanted to do the same thing with multiple div. But here if I am selecting yes then both the div are open. And not close to clicked on no value.
Here is my code:
class PersonalInfo extends Component {
constructor(props) {
super(props);
this.divstatus1 = this.divstatus1.bind(this);
this.divstatus2 = this.divstatus2.bind(this);
this.state = {
value1: 'no',
value2: 'no'
};
}
divstatus1 = (e) => {
this.setState({ value1: e.target.value1 });
}
divstatus2 = (e) => {
this.setState({ value2: e.target.value2 });
}
render() {
return (
<div>
<h3 className="showbase_header">Passport Details</h3>
<div className="form-group">
<label htmlFor="orderby"> Do you have passport ?</label>
<select className="form-control orderby" onChange={this.divstatus1}>
<option value="" selected>Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br></br>
<div className={this.state.value1} >
<div className="row">
<div className="col-md-6 form-group">
<label htmlFor="name">Passport Number
<span className="required">*</span>
</label>
<input type="text" id="firstname" aria-required="true" size={30} name="firstname" className="form-control" placeholder="" />
</div>
<div className="col-md-6 form-group">
<label htmlFor="name">Place Of Issue
<span className="required">*</span>
</label>
<input type="text" id="lastname" aria-required="true" size={30} name="lastname" className="form-control" placeholder="" />
</div>
</div>
<div className="row">
<div className="col-sm-6 form-group">
<label htmlFor="expirydate">Expiry Date
<span className="required">*</span>
</label>
<input type="date" id="expirydate" aria-required="true" size={30} name="expirydate" className="form-control" placeholder="" />
</div>
<div className="col-sm-6 form-group">
<label htmlFor="issuedate">Issue Date
<span className="required">*</span>
</label>
<input type="date" id="issuedate" aria-required="true" size={30} name="issuedate" className="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div className="form-group">
<h3 className="showbase_header">Representation</h3>
<select className="form-control orderby" onChange={this.divstatus2}>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select><br />
<div className={this.state.value2} >
<div class="row">
<div className="col-sm-6 form-group">
<label htmlFor="name">Name
<span className="required">*</span>
</label>
<input type="text" id="name" aria-required="true" size={30} name="name" className="form-control" placeholder="" />
</div>
<div className="col-sm-6 form-group">
<label htmlFor="number">Contact Number
<span className="required">*</span>
</label>
<input type="number" id="name" aria-required="true" size={30} name="number" className="form-control" placeholder="" />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default PersonalInfo;
I have added in main.css
.yes{display: block;}
.no{display: none;}

Can you try this,
divstatus1 = (e) => {
this.setState({ value1: e.target.value });
}
divstatus2 = (e) => {
this.setState({ value2: e.target.value });
}
option does not have an attribute called value1 or value2

Related

How save input values and checked information in state?

I made such a project through context. But I can't save the values of checkbox and select options in memory. All other inputs work correctly. CRUD operations are fine, but when I select and confirm the gender, then when I try to edit the details of that contact, the gender of the contact is not visible. Also, the ``I want to receive information'' button at the bottom does not appear checked.
import React, { useState } from "react";
import { useContext } from "react";
import { GlobalContext } from "../../context/GlobalState";
import { useNavigate } from "react-router-dom";
import { NavLink } from "react-router-dom";
import { v4 as uuidv4 } from 'uuid';
const Form = () => {
const { ADD_CONTACT } = useContext(GlobalContext);
const [contact, setContact] = useState({
id: uuidv4(),
name: "",
surname: "",
fatherName: "",
specialty: "",
email: "",
gender: "",
updatesNotification:''
});
const { name, surname, fatherName, specialty, email } = contact;
let history = useNavigate();
const onSubmit = (e) => {
e.preventDefault();
if (contact) {
ADD_CONTACT(contact);
history("/contacts");
console.log(contact);
}
};
return (
<form onSubmit={onSubmit}>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input
class="form-control"
name="name"
required
value={name}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Surname</label>
<div class="col-sm-10">
<input
class="form-control"
name="surname"
required
value={surname}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Father Name</label>
<div class="col-sm-10">
<input
class="form-control"
name="fatherName"
required
value={fatherName}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input
class="form-control"
name="email"
required
value={email}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Specialty</label>
<div class="col-sm-10">
<input
class="form-control"
name="specialty"
required
value={specialty}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
</div>
</div>
<div className="mb-3 row">
<label class="col-sm-2 col-form-label">Job</label>
<div className="col-sm-10 d-flex justify-content-center align-items-center">
<select class="form-select" aria-label="Default select example">
<option selected>Bakalavr</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
</div>
<div className="mb-3 row">
<label class="col-sm-2 col-form-label">Gender</label>
<div className="col-sm-10">
<div class="form-check form-check-inline ">
<input
class="form-check-input"
type="radio"
name="gender"
value="male"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
<label class="form-check-label">Kisi</label>
</div>
<div class="form-check form-check-inline">
<input
class="form-check-input"
type="radio"
name="gender"
value="female"
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.value })
}
/>
<label class="form-check-label">Female</label>
</div>
</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" />
<label class="form-check-label" for="flexCheckDefault">
I want to be notified of updates
</label>
</div>
<button type="submit" class="btn btn-primary">
Create a new contact
</button>
<NavLink to="/contacts" className="btn btn-danger m-2">
Cancel
</NavLink>
</form>
);
};
export default Form;
import React from "react";
import { NavLink } from "react-router-dom";
import { useContext, useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { GlobalContext } from "../../context/GlobalState";
const EditContactForm = () => {
const { contacts, UPDATE_CONTACT } = useContext(GlobalContext);
const [selectedContact, setSelectedContact] = useState({
id: "",
name: "",
surname: "",
fatherName: "",
specialty: "",
email: "",
gender: "",
});
const history = useNavigate();
const {id} = useParams();
useEffect(() => {
const userId = id;
const selectedContact = contacts.find((user) => String(user.id) === userId);
if (selectedContact) {
setSelectedContact(selectedContact);
}
}, [id, contacts]);
function onSubmit(e) {
e.preventDefault();
UPDATE_CONTACT(selectedContact);
console.log("new user edited:", selectedContact);
history("/contacts");
}
const handleOnChange = (e) => {
setSelectedContact(selectedContact => ({
...selectedContact,
[e.target.name]: e.target.value
}));
};
return (
<div>
<form onSubmit={onSubmit}>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input
class="form-control"
name="name"
required
value={selectedContact?.name ?? ''}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Surname</label>
<div class="col-sm-10">
<input
class="form-control"
name="surname"
required
value={selectedContact?.surname ?? ''}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Father Name</label>
<div class="col-sm-10">
<input
class="form-control"
name="fatherName"
required
value={selectedContact?.fatherName ?? ''}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input
class="form-control"
name="email"
required
value={selectedContact?.email ?? ''}
onChange={handleOnChange}
/>
</div>
</div>
<div class="mb-3 row">
<label class="col-sm-2 col-form-label">Specialty</label>
<div class="col-sm-10">
<input
class="form-control"
name="specialty"
required
value={selectedContact?.specialty ?? ''}
onChange={handleOnChange}
/>
</div>
</div>
<div className="mb-3 row">
<label class="col-sm-2 col-form-label">Vezife</label>
<div className="col-sm-10 d-flex justify-content-center align-items-center">
<select class="form-select" aria-label="Default select example">
<option selected>Bakalavr</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
</div>
<div className="mb-3 row">
<label class="col-sm-2 col-form-label">Gender</label>
<div className="col-sm-10">
<div class="form-check form-check-inline ">
<input
class="form-check-input"
type="radio"
name="gender"
required
value="male"
onChange={handleOnChange}
/>
<label class="form-check-label">Male</label>
</div>
<div class="form-check form-check-inline">
<input
class="form-check-input"
type="radio"
name="gender"
value="female"
onChange={handleOnChange}
/>
<label class="form-check-label">Female</label>
</div>
</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" />
<label class="form-check-label" for="flexCheckDefault">
I want to be notified of updates
</label>
</div>
<button type="submit" class="btn btn-primary">
Update a contact
</button>
<NavLink to="/contacts" className="btn btn-danger m-2">
Cancel
</NavLink>
</form>
</div>
);
};
export default EditContactForm;
enter image description here
enter image description here
sandbox: https://codesandbox.io/s/task1-w5zvg4?file=/src/App.js
When working with checkbox you have to look for e.target.checked to access if it is checked or not.
You can try something like this:
<div class="form-check form-check-inline">
<input
class="form-check-input"
type="radio"
name="gender"
id="female"
checked={contact.gender === "female"}
onChange={(e) =>
setContact({ ...contact, [e.target.name]: e.target.checked ? e.target.id : "" })
}
/>
<label htmlFor="female" class="form-check-label">Female</label>
</div>
For the select, you can achieve this like this:
const selectOptions = [
{label: "One", value: 1},
{label: "Two", value: 2},
{label: "Three", value: 3},
]
const Test = () => {
const onChange = (e) => setContact({ ...contact, [e.target.name]: e.target.value })
return <>
<label class="col-sm-2 col-form-label">Job</label>
<div className="col-sm-10 d-flex justify-content-center align-items-center">
<select value={contact.test} onChange={onChange} name="test" class="form-select" aria-label="Default select example">
{selectOptions.map(item => (
<option key={item.value} value={item.value}>{item.label}</option>
))}
</select>
</div>
</>
}

Changing state in useEffect

I am dispatching an action in useEffect hook to fetch data and then updating state using the data from redux store. When the page first loads i get the correct data, but when refreshing the browser I get undefined values.
React.useEffect(() => {
dispatch(getSingleCoin(props.match.params.id))
setName(coinDetail.name)
setSymbol(coinDetail.symbol)
setLogourl(coinDetail.logo)
setPrice(coinDetail.price)
setLaunchDate(coinDetail.launchDate)
setWebsiteUrl(coinDetail.websiteUrl)
setNetwork(coinDetail.chain)
setAddress(coinDetail.address)
setTwitterUrl(coinDetail.twitter)
setTelegramUrl(coinDetail.telegram)
setRedditUrl(coinDetail.reddit)
setYoutubeUrl(coinDetail.youtube)
setCoinDescription(coinDetail.description)
setMarketCap(coinDetail.marketCap)
}
}, [coinDetail,dispatch, props.match.params.id])
const handleSubmit = (e) => {
e.preventDefault()
const coin = {}
coin.name = name
coin.symbol = symbol
coin.logo = logourl
coin.price = price
coin.launchDate = launchDate
coin.websiteUrl = websiteUrl
coin.chain = network
coin.address = address
coin.twitter = twitterUrl
coin.telegram = telegramUrl
coin.reddit = redditUrl
coin.youtube = youtube
coin.description = coinDescription
coin.marketCap = marketCap
coin._id = props.match.params.id
dispatch(updateCoin(coin))
}
return (
<div className="container add-coin-wapper mt-4">
{loading && coinDetail === undefined ? (
<div>...Loading</div>
) : error ? (
<div>{error}</div>
) : (
<div className="card ">
<div className="card-header">
<div className="approve-header">
<div
className="approve-back"
onClick={() => props.history.push('/Admin/coinlist')}
>
<ArrowBackIosIcon />
<div>Back to Coin listing</div>
</div>
</div>
</div>
<div className="card-body">
{/* here */}
<>
<div>
<h3>Edit Coin</h3>
</div>
<form onSubmit={handleSubmit}>
<div className="row">
<div className="col-sm-12 col-md-6 col-lg-6">
<h5>Coin informations</h5>
<div className="form-group">
<label htmlFor="name">name</label>
<input
type="text"
className="form-control"
id="name"
name="name"
placeholder="Bitcoin"
required
onChange={(e) => setName(e.target.value)}
value={name}
/>
</div>
<div className="form-group">
<label htmlFor="symbol">symbol</label>
<input
type="text"
className="form-control"
id="symbol"
name="symbol"
placeholder="Enter symbol"
onChange={(e) => setSymbol(e.target.value)}
required
value={symbol}
/>
</div>
<div className="form-group">
<label htmlFor="logo">Logo url</label>
<input
type="text"
className="form-control"
id="url"
name="logourl"
placeholder="https://clod.com/logo"
onChange={(e) => setLogourl(e.target.value)}
value={logourl}
/>
</div>
<div className="form-group">
<label htmlFor="description">Coin Description</label>
<textarea
className="form-control"
id="exampleFormControlTextarea1"
rows="3"
onChange={(e) => setCoinDescription(e.target.value)}
placeholder="Describe your coin appropriately to show attractiveness"
value={coinDescription}
></textarea>
</div>
<div className="form-group">
<label htmlFor="price">price</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">$</div>
</div>
<input
type="number"
className="form-control"
id="marketcap"
placeholder="0.00085"
step="any"
min="0"
onChange={(e) => setPrice(e.target.value)}
value={price}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="marketcap">Market cap</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">$</div>
</div>
<input
type="number"
className="form-control"
id="marketcap"
step="any"
placeholder="0.00085"
min="0"
onChange={(e) => setMarketCap(e.target.value)}
value={marketCap}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="launchdate">Launch date</label>
<div
className="input-group date"
data-provide="datepicker"
>
<input
type="date"
className="form-control"
onChange={(e) => setLaunchDate(e.target.value)}
value={moment(launchDate).format('YYYY-MM-DD')}
/>
<div className="input-group-addon">
<span className="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-6 col-lg-6">
<h5>Coin market</h5>
<div className="form-group">
<label htmlFor="network">Network/Chain</label>
<select
className="form-control"
id="network"
onChange={(e) => setNetwork(e.target.value)}
value={network}
>
<option value="BSC">Binance Smart Chain (BSC)</option>
<option value="ETH">Ethereum (ETH)</option>
<option value="SOL">Solona (SOL)</option>
</select>
</div>
<div className="form-group">
<label htmlFor="contract">Contract Adress</label>
<input
type="text"
className="form-control"
id="contract"
name="contract"
placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
onChange={(e) => setAddress(e.target.value)}
required
value={address}
/>
</div>
<h5>Coin links</h5>
<div className="form-group">
<label htmlFor="weburl">Website url</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<LanguageIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="web"
placeholder="https://www.coinx.com"
onChange={(e) => setWebsiteUrl(e.target.value)}
required
value={websiteUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="twitter">Twitter</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<TwitterIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="twitter"
placeholder="https://twitter.com/"
onChange={(e) => setTwitterUrl(e.target.value)}
value={twitterUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="telegram">Telegram</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<TelegramIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="telegram"
placeholder="https://t.me/"
onChange={(e) => setTelegramUrl(e.target.value)}
value={telegramUrl}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="youtube">YouTube</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<YouTubeIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="youtube"
placeholder="https://www.youtube.com/watch?v="
onChange={(e) => setYoutubeUrl(e.target.value)}
value={youtube}
/>
</div>
</div>
<div className="form-group">
<label htmlFor="reddit">Reddit</label>
<div className="input-group mb-2">
<div className="input-group-prepend">
<div className="input-group-text">
<RedditIcon />
</div>
</div>
<input
type="text"
className="form-control"
id="reddit"
placeholder="https://www.reddit.com"
onChange={(e) => setRedditUrl(e.target.value)}
value={redditUrl}
/>
</div>
</div>
<button type="submit" className="btn" disabled={loading}>
update
</button>
</div>
</div>
</form>
</>
{/* here */}
</div>
{/* here */}
</div>
)}
</div>
The state data is supposed to be displayed in form input elements. I render a div with a loading status before the data is fetched and loading set to false.

What could cause html select element not to render on the browser?

I have a form in my react project with few input tags
and select tags. On the browser the inputs are rendering
but the select tags are not rendering. I am using materialize css
for the styling. I inspect the elements, the select element is showing
on the elements inspection pane and there is no console error about it.
What could be the problem and the possible
solution? The codes is as show below with screen shots.
import React, { useState, useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import M from 'materialize-css/dist/js/materialize'
function Register() {
const initialState = {
pin: '',
serial_num: '',
last_name: '',
first_name: '',
date: '',
gender: 'male',
school: '',
class: '',
photo: ''
}
const photoRef = useRef();
const dispatch = useDispatch();
useEffect(() => {
const elems = document.querySelectorAll('.datepicker');
M.Datepicker.init(elems, {
autoClose: true
});
}, []);
const [regState, setRegState] = useState(initialState)
const onChange = e => {
setRegState({ ...regState, [e.target.name]: e.target.value });
}
const onSubmit = e => {
// dispatch();
setRegState({...regState,
photo: photoRef.current.files[0].name
})
console.log(regState)
console.log(photoRef.current.files[0].name);
setRegState({ ...initialState });
e.preventDefault();
}
return (
<div className="row">
<form method='POST'
onSubmit={onSubmit}
className="col s12"
encType="multipart/form-data"
>
<div className="input-field col s12">
<input id="serial_num" type="text"
className="validate" name="serial_num"
min="13" max="17" onChange={onChange} required
value={regState.serial_num}
/>
<label htmlFor="serial_num">Serial Number</label>
</div>
<div className="input-field col s12">
<input id="pin" type="password"
className="validate" name="pin"
min="10" max="15" onChange={onChange} required
value={regState.pin}
/>
<label htmlFor="pin">Pin</label>
</div>
<div className="input-field col s12">
<input id="last_name" type="text"
className="validate" name="last_name"
onChange={onChange} required
value={regState.last_name}
/>
<label htmlFor="last_name">Last Name</label>
</div>
<div className="input-field col s12">
<input id="first_name" type="text"
className="validate" name="first_name"
onChange={onChange} required
value={regState.first_name}
/>
<label htmlFor="first_name">First Name</label>
</div>
<div className="input-field col s12">
<input id="date" type="text"
className="validate datepicker" name="date"
onChange={onChange} required
value={regState.date}
/>
<label htmlFor="date">Date of Birth</label>
</div>
<div className="input-field col s12">
<label>
<input name="gender" type="radio" checked value='male' onChange={onChange} />
<span>Male</span>
</label>
</div>
<div className="input-field col s12">
<label>
<input name="gender" type="radio" value='female' onChange={onChange} />
<span>Female</span>
</label>
</div>
<div className="input-field col s12">
<select name='school' id="school" value={regState.school} onChange={onChange} >
<option value="" >Select School</option>
<option value="nursery" >Nursery School</option>
<option value="primary" >Primary School</option>
<option value="secondary" >Secondary School</option>
</select>
<label htmlFor="school">Select School</label>
</div>
<div className="input-field col s12">
<select name='class' id="class" value={regState.class} onChange={onChange} >
<option value="" >Select Class</option>
</select>
<label htmlFor="class">Select Class</label>
</div>
<div className="input-field col s12">
<input id="photo" type="file"
className="validate" name="photo"
ref={photoRef}
/>
<label htmlFor="photo">Photo</label>
</div>
<button className="btn waves-effect waves-light" type="submit" name="action">Submit
<i className="material-icons right">send</i>
</button>
</form>
</div>
)
}
Select needs to be initialized - after it's been added to the DOM, and every subsequent time it is rendered:
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
FYI, Materialize hides the native select (display:none) and only generates the new select (actually a dropdown triggered by a text input) when the init runs. You can also use .browser-default on the select and bypass the init and the materialize styling.

How to enable/ disable react form based on condition

I have an react js form.I would like to know how to enable/disable all form input control based on condition.please check my below code and advise how to do this...
return (
<form id ="frm" onSubmit={this.onSubmitHandler}>
<div className="animated fadeIn">
<div className="form-group row">
<Button type="button" text="Back" size="sm" onClick={this.onBackButtonClick} color="danger" className="pull-right ml-1 "><i className="fa fa-ban"></i> Back</Button>
<Button type="submit" size="sm" color="success" className="pull-right ml-1 "><i className="fa fa-dot-circle-o"></i> Save</Button>
<label className="col-sm-1 col-form-label col-form-label-sm">First Name</label>
<div className="col-sm-3">
<input type="text" name="FirstName" className="form-control form-control-sm" id="TxtFirstName" placeholder="First Name" value={this.state.FirstName} required onChange={this.onChangeHandler}/>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Last Name</label>
<div className="col-sm-3">
<input type="text" name="LastName" className="form-control form-control-sm" id="TxtLastName" placeholder="Last Name" value={this.state.LastName} required onChange={this.onChangeHandler}/>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Email Id</label>
<div className="col-sm-3">
<input type="email" name ="EmailId" className="form-control form-control-sm" id="TxtEmailId" placeholder="EmailId" value={this.state.EmailId} required onChange={this.onChangeHandler}/>
</div>
</div>
<div className="form-group row">
<label className="col-sm-1 col-form-label col-form-label-sm">Mobile No</label>
<div className="col-sm-3">
<input type="text" name ="MobileNo" className="form-control form-control-sm" id="TxtMobileNo" placeholder="Mobile No" value={this.state.MobileNo} onChange={this.onChangeHandler} />
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Division</label>
<div className="col-sm-3">
<select name ="DivisionId" className="form-control" required value={this.state.DivisionId} onChange={this.onChangeHandler}>
{DivisionList}
</select>
</div>
/div>
</form>
);
ComponentDidMount Event to check condition :-
componentDidMount() {
if (this.props.match.params.mode=="Edit"){
// enable form control
}
else
{
// disable form control
}
create a state isFormDisabled for ex.
use html fieldset inside the form and use disabled property and provide the value of isFormDisabled
use your logic to enable/disable based on your needs
Code Sample
...
state = {
isFormDisabled: false
}
componentDidMount(){
if (this.props.match.params.mode == "Edit") {
this.setState({isFormDisabled: false})
}
else {
this.setState({isFormDisabled: true})
}
}
...
//inside render fun...
return (
<form id ="frm" onSubmit={this.onSubmitHandler}>
<fieldset disabled={isFormDisabled}>
<div className="animated fadeIn">
<div className="form-group row">
<label className="col-sm-1 col-form-label col-form-label-sm">First Name</label>
<div className="col-sm-3">
<input type="text" name="FirstName" className="form-control form-control-sm" id="TxtFirstName" placeholder="First Name" value={this.state.FirstName} required onChange={this.onChangeHandler}/>
</div>
...
</fieldset>
...

React conditional divs with hooks

I am creating a signup form that will render differently depending on whether the person signing up chooses Post a project or Work on a project from the very first div in the form.
How can I render each div that follows in the form-group conditionally based on what is selected in the first div? I am using hooks and I have found that most examples are for the extends Component approach.
My form:
const signUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select onChange={handleChange("role")} class="form-control">
<option selected>I want to...</option>
<option>Post a project</option>
<option>Work on a project</option>
</select>
</div>
<div className="form-group">
<input
onChange={handleChange("name")}
type="text"
placeholder="Name"
className="form-control"
value={name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("email")}
type="email"
placeholder="Email"
className="form-control"
value={email}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("password")}
type="password"
placeholder="Password"
className="form-control"
value={password}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("studying")}
type="text"
placeholder="I'm studying..."
className="form-control"
value={studying}
/>
</div>
<div>
<div>{createInputs()}</div>
<button
className="btn btn-outline-primary btn-sm mb-3"
onClick={addSkill}
type="text"
>
Add more skills
</button>
</div>
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);
State:
const Signup = () => {
const [values, setValues] = useState({
name: "",
email: "",
password: "",
studying: "",
skills: [""],
error: "",
success: "",
role: ""
});
const { name, email, password, studying, skills, success, error, role } = values;
handleChange():
const handleChange = name => event => {
setValues({ ...values, error: false, [name]: event.target.value });
};
You should first divide the signUp in two parts and then call second function based on value of "role" from state.
The idea is to return the divs from second function based on state of first input.
const signUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select onChange={handleChange("role")} class="form-control">
<option selected>I want to...</option>
<option>Post a project</option>
<option>Work on a project</option>
</select>
</div>
{this.renderInput()}
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);
renderInput() {
if (values.role === "post") {
return (
<div className="form-group">
<input onChange={handleChange("name")} type="text" placeholder="Name" className="form-control" value={name} />
</div>
<div className="form-group">
<input onChange={handleChange("email")} type="email" placeholder="Email" className="form-control" value={email} />
</div>
<div className="form-group">
<input onChange={handleChange("password")} type="password" placeholder="Password" className="form-control" value={password} />
</div>
<div className="form-group">
<input onChange={handleChange("studying")} type="text" placeholder="I'm studying..." className="form-control" value={studying} />
</div>
<div>
<div>{createInputs()}</div>
<button className="btn btn-outline-primary btn-sm mb-3" onClick={addSkill} type="text">
Add more skills
</button>
</div>
);
}
}
You want to test the role state value is truthy/falsey and render the rest of your form on that value.
const SignUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select
defaultValue='unselected' // set default value here
onChange={handleChange("role")}
className="form-control" // fix className here, class alone isn't correct in react
>
<option value='unselected'>I want to...</option>
<option value='post'>Post a project</option>
<option value='work'>Work on a project</option>
</select>
</div>
{!!role && (
<Fragment>
<div className="form-group">
<input
onChange={handleChange("name")}
type="text"
placeholder="Name"
className="form-control"
value={name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("email")}
type="email"
placeholder="Email"
className="form-control"
value={email}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("password")}
type="password"
placeholder="Password"
className="form-control"
value={password}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("studying")}
type="text"
placeholder="I'm studying..."
className="form-control"
value={studying}
/>
</div>
<div>
<div>{createInputs()}</div>
<button
className="btn btn-outline-primary btn-sm mb-3"
onClick={addSkill}
type="text"
>
Add more skills
</button>
</div>
</Fragment>
)}
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);

Resources