In the below form component how can we hide the certain input components ?
#1 how can we pass display: none to certain component?
#2 tried to set the state and mount but throwing errors while rendering.
const inputStyle = {
display:none
}
and pass the style = {inputStyle} to effect certain components
is there any effective way to condtionally render the below form and hide the different components for different domains?
import React from 'react'
class ClassComponentForm extends React.Component {
state = {}
componentDidMount(){
this.setState(emptyForm)
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render(){
return(
<div id='classComponentForm'>
<h2>
Please Enter Your Information - Class
</h2>
<form id='form'>
<label htmlFor='nameInput'>
Name:
</label>
<input
id='nameInput'
name='name'
type='text'
placeholder='Please type your name'
value={this.state.name}
onChange={(e) => this.handleChange(e)}
/>
<label htmlFor='emailInput'>
Email:
</label>
<input
id='emailInput'
name='email'
type='text'
placeholder='Please type your email'
value={this.state.email}
onChange={(e) => this.handleChange(e)}
/>
<label htmlFor='zipcodeInput'>
Zipcode:
</label>
<input
id='zipcodeInput'
name='zipcode'
type='text'
placeholder='Please type your zipcode'
value={this.state.zipcode}
onChange={(e) => this.handleChange(e)}
/>
<label htmlFor='dateInput'>
Date:
</label>
<input
id='dateInput'
name='date'
type='date'
value={this.state.date}
onChange={(e) => this.handleChange(e)}
/>
</form>
</div>
)
}
}
export default ClassComponentForm
handleChange setup keys inside state object based on input name (because of e.target.name) which you defined in the input element. You already access this value inside the value prop
value={this.state.email}
The same thing can be used to conditionally hide each input. This is an example of how you can hide email input.
{this.state.email && <input
id='emailInput'
name='email'
type='text'
placeholder='Please type your email'
value={this.state.email}
onChange={(e) => this.handleChange(e)}
/>}
Related
Below is a authentication component that handles both registering and login of a user into an application. The approach used was to conditionally render a div based on whether a user had signed up in the application before or they are a new user. The div doesn't change based on the initial state and based on the conditions set. In this case, the isSignUp state is false therefore the user hasn't signed up before hence all the fields are supposed to be available for data input by the user but the fields have been ommited. Below is the code
const {isSignUp, setisSignUp} = useState(false);
<form onSubmit = {handleSubmit} className = 'form'>
{isSignUp && (
<div className='auth-form-field'>
<input
name="Full Name"
type="text"
placeholder="Full Name"
className = "form-input"
onChange={handleChange}
required
/>
</div>
)}
<div className='auth-form-field'>
<input
name="Email"
type="text"
placeholder="Email"
className = "form-input"
onChange={handleChange}
required
/>
</div>
{ isSignUp && (
<div className='auth-form-field'>
<input
name="User Name"
type="text"
placeholder="User Name"
className = "form-input"
onChange={handleChange}
required
/>
</div>)
}
<div className = 'auth-form-field'>
<input
name="Password"
type="password"
placeholder="Password"
className = "form-input"
onChange={handleChange}
required
/>
</div>
{isSignUp && (
<div className = 'auth-form-field'>
<input
name="Confirm Password"
type="password"
placeholder="Confirm Password"
className = "form-input"
onChange={handleChange}
required
/>
</div>)
}
</form>
Your syntax of useState is incorrect here
Correct syntax:
const [isSignUp, setisSignUp] = useState(false);
The Correct syntax to use useState is with square brackets, like this
const [isSignup, setIsSignUp] = useState(false);
This checkbox is permanently checked, I want the pre selected checkbox to change the boolean state. I'm currently using this handleChange method to deal with text inputs. Do I have to create another method to deal with the checkbox or can I add to the existing method?
state = {
billingEmail:'',
billingAddressSame: true,
}
handleChange = input => e => {
this.setState({[input]: e.target.value})
}
<input
className="col-sm-12"
type="email"
placeholder="Email"
onChange={handleChange('billingEmail')}
defaultValue={values.billingEmail}
/>
<label className="col-sm-12" style={{paddingLeft: "0"}}>
<input
type="checkbox"
checked={values.billingAddressSame}
onChange={handleChange('billingAddressSame')}
/>
Same as company address
</label>
Change your handleChange function to
handleChange = input => e => {
this.setState({[input]: !this.state[input]})
}
You can control your checkbox and input by a single method.
See
Constructor and handle change function-
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
And in your render function -
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
See this for more info
try this and let me know, its working fine for me
import React, { Component, Fragment } from 'react';
class SignUp extends Component{
state = {
billingEmail:'',
billingAddressSame: true,
}
render(){
return(<Fragment>
<input className="input" type="email" className="col-sm-12" placeholder="Email" value={this.state.billingEmail} onChange={e => this.setState({billingEmail: e.target.value})}/>
<label className="col-sm-12" style={{paddingLeft: "0"}}>
<input type="checkbox" value="CheckBox1" checked={this.state.billingAddressSame} onChange={e => this.setState({ billingAddressSame: !this.state.billingAddressSame })} />
Same as company address
</label>
</Fragment>)
}
}
export default SignUp;
I have three inputs, and I want each input's data to be stored in a state. For example, the name input should be stored in the name state, because I'll need it later to push the three states' values in a firebase database.
I used the onChange function to store the data, but I didn't know how to make each input's function relative to the state I want to put it in.
import React from "react";
import ReactDOM from "react-dom";
export default class Inputs extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
age: ""
};
}
handleChange = e => {
this.setState({ name: e.target.value });
};
render() {
return (
<div>
<form>
<label>
name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<label>
email:
<input type="text" name="email" onChange={this.handleChange} />
</label>
<label>
age:
<input type="text" name="age" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<textarea value={this.state.value} onChange={this.handleChange} />
<button onClick={() => this.props.onClick(this.state.value)}>
Add task
</button>
</div>
);
}
}
getChanges = (e) => {
console.log(e);
this.setState({[e.target.name]: e.target.value}, function () {
console.log(this.state)
})
};
call this function,
<Input onChange={(e) => this.getChanges(e)} name={'name'}
value={this.state.name} placeholder={'Name'}/>
You can pass key and value
<input type="text" name="name" onChange={(event)=>this.handleChange(event,'name')} />
and in your function you can do something like this
handleChange = (e,key) => {
this.setState({ [key] : e.target.value });
};
I am getting this error, I am new in react. I have seen other posts but still could not resolve the issue. help will be appreciated. thanks
Warning: A component is changing an uncontrolled input of type email to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info
in input (created by Edit)
in div (created by Edit)
in div (created by Edit)
in form (created by Edit)
in div (created by Edit)
in Edit
import React from 'react'
import ReactDom from 'react-dom'
export default class Edit extends React.Component{
constructor(){
super();
this.state={
name: '',
email: '',
password: '',
};
}
componentWillMount(){
let id=this.props.id;
axios.get('/api/users/'+id).then(response => {
var user= response.data;
this.setState({
name: user.name,
email: user.email,
})
}).catch(error => {
console.log(error)
})
}
handleNameChange(e){
this.setState({
name: e.target.value
})
}
handleEmailChange(e){
this.setState({
email: e.target.value
})
}
handlePasswordChange(e){
this.setState({
password: e.target.value
})
}
handleSubmit(e){
e.preventDefault();
console.log(this.state)
axios.post('/api/users',this.state).then(response => {
console.log(response)
}).then(error => {
console.log(error)
})
}
render(){
return(
<div>
<h2> Add New User </h2>
<form className="form-horizontal" onSubmit={this.handleSubmit.bind(this)}>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="email">Name:</label>
<div className="col-sm-10">
<input type="text" className="form-control" id="name" placeholder="Enter name" value={this.state.name}
onChange={ this.handleNameChange.bind(this) }/>
</div>
</div>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="email">Email:</label>
<div className="col-sm-10">
<input type="email" className="form-control" id="email" placeholder="Enter email" value={this.state.email}
onChange={ this.handleEmailChange.bind(this) }/>
</div>
</div>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="email">Password:</label>
<div className="col-sm-10">
<input type="password" className="form-control" id="password" placeholder="Enter password" value={this.state.password}
onChange={ this.handlePasswordChange.bind(this) }/>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-default">Update</button>
</div>
</form>
</div>
)
}
}
if (document.getElementById('edit')) {
var id=$("#edit").data("id");
ReactDom.render(<Edit id={id}/>, document.getElementById('edit'))
}
You are using value attribute to set default value while rendering, it makes your input controlled input, then when updating your states you are trying to change your input values again which will make it uncontrolled one. basically for your code to succeed you need to use defaultValue attribute in your rendered code instead of value attr. because when you are setting value to input from html it can't be later changed.
do this instead for your input elements:
<input type="email" className="form-control" id="email" placeholder="Enter email" defaultValue={this.state.email} />
here is a source from react docs on issue:
https://reactjs.org/docs/uncontrolled-components.html
The error is occuring because when you're doing setState inside componentDidMount, the value returned seems to be undefined.
if(user.name!==undefined && user.email!==undefined){
this.setState({
name: user.name,
email: undefined,
})
}
This will prevent the values in the state from becoming undefined and you won't have that error anymore.
i am trying to get the multiple form fields input values and sending that to server. But i am only able to get the last field's value on submit.
I am using uncontrolled component because i am trying to editing the form and then updating it.Please help me out to get all the form details entered in the form.
import React from 'react';
import axios from 'axios';
class Update extends React.Component {
constructor(props) {
super(props);
this.state = {
info:''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
console.log(event);
alert(event);
}
componentDidMount(){
let self = this;
axios.get('http://localhost:8080/studentById')
.then(function(data) {
//console.log(data);
self.setState({info:data.data});
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} >
<label className="w3-label w3-text-blue w3-large w3-margin-0 ">
First Name:
<input autoFocus type="text" className="w3-input w3-border" defaultValue={this.state.info.Firstname} ref={(input) => this.input = input} required />
</label>
<label className="w3-label w3-text-blue w3-large">
Last Name:
<input type="text" className="w3-input w3-border" defaultValue={this.state.info.Lastname} ref={(input) => this.input = input} required />
</label>
<input className="w3-btn-block w3-blue w3-margin-bottom w3-large" type="submit" value="Submit" />
</div>
)};
}
In your code, you assign all refs to the same variable. (your code simplified for showing what I mean)
First Name:
<input ref={(input) => this.input = input} />
Last Name:
<input ref={(input) => this.input = input} />
Instead use different variable for different input fields:
First Name:
<input ref={(input) => this.firstNameInput = input} />
Last Name:
<input ref={(input) => this.lastNameInput = input} />
You should use different property names for each input inside refs callbacks (currently you override this.input so it points to the last input):
<input autoFocus type="text" className="w3-input w3-border" defaultValue={this.state.info.Firstname} ref={(input) => this.input1 = input} required />
<input autoFocus type="text" className="w3-input w3-border" defaultValue={this.state.info.Firstname} ref={(input) => this.input2 = input} required />
Then inside your component methods you can access value of an input this way:
let inputValue = this.input1.value;