How to set default Checked in checkbox ReactJS? - reactjs

I'm having trouble to update the checkbox state after it's assigned with default value checked="checked" in React.
var rCheck = React.createElement('input',
{
type: 'checkbox',
checked: 'checked',
value: true
}, 'Check here');
After assigning checked="checked", I cannot interact the checkbox state by clicking to uncheck/check.

To interact with the box you need to update the state for the checkbox once you change it. And to have a default setting you can use defaultChecked.
An example:
<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />

There are a few ways to accomplish this, here's a few:
Written using State Hooks:
function Checkbox() {
const [checked, setChecked] = React.useState(true);
return (
<label>
<input type="checkbox"
defaultChecked={checked}
onChange={() => setChecked(!checked)}
/>
Check Me!
</label>
);
}
ReactDOM.render(
<Checkbox />,
document.getElementById('checkbox'),
);
Here is a live demo on JSBin.
Written using Components:
class Checkbox extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked: true,
};
}
toggleChange = () => {
this.setState({
isChecked: !this.state.isChecked,
});
}
render() {
return (
<label>
<input type="checkbox"
defaultChecked={this.state.isChecked}
onChange={this.toggleChange}
/>
Check Me!
</label>
);
}
}
ReactDOM.render(
<Checkbox />,
document.getElementById('checkbox'),
);
Here is a live demo on JSBin.

If the checkbox is created only with React.createElement then the property
defaultChecked is used.
React.createElement('input',{type: 'checkbox', defaultChecked: false});
Credit to #nash_ag

In the React rendering lifecycle, the value attribute on form elements
will override the value in the DOM. With an uncontrolled component,
you often want React to specify the initial value, but leave
subsequent updates uncontrolled. To handle this case, you can specify
a defaultValue or defaultChecked attribute instead of value.
<input
type="checkbox"
defaultChecked={true}
/>
Or
React.createElement('input',{type: 'checkbox', defaultChecked: true});
Please checkout more details regarding defaultChecked for checkbox below:
https://reactjs.org/docs/uncontrolled-components.html#default-values

in addition to the correct answer you can just do :P
<input name="remember" type="checkbox" defaultChecked/>

import React, { useState } from 'react'
const [rememberUser, setRememberUser] = useState(true) //use false for unchecked initially
<input
type="checkbox"
checked={rememberUser}
onChange={() => {
setRememberUser(!rememberUser)
}}
/>

Value would be whether true or false defaultChecked={true}
<input type="checkbox"
defaultChecked={true}
onChange={() => setChecked(!checked)}
/>

It`s working
<input type="checkbox" value={props.key} defaultChecked={props.checked} ref={props.key} onChange={this.checkboxHandler} />
And function init it
{this.viewCheckbox({ key: 'yourKey', text: 'yourText', checked: this.state.yourKey })}

You may pass "true" or "" to the checked property of input checkbox. The empty quotes ("") will be understood as false and the item will be unchecked.
let checked = variable === value ? "true" : "";
<input
className="form-check-input"
type="checkbox"
value={variable}
id={variable}
name={variable}
checked={checked}
/>
<label className="form-check-label">{variable}</label>

I tried to accomplish this using Class component:
you can view the message for the same
.....
class Checkbox extends React.Component{
constructor(props){
super(props)
this.state={
checked:true
}
this.handleCheck=this.handleCheck.bind(this)
}
handleCheck(){
this.setState({
checked:!this.state.checked
})
}
render(){
var msg=" "
if(this.state.checked){
msg="checked!"
}else{
msg="not checked!"
}
return(
<div>
<input type="checkbox"
onChange={this.handleCheck}
defaultChecked={this.state.checked}
/>
<p>this box is {msg}</p>
</div>
)
}
}

Here's a code I did some time ago, it might be useful.
you have to play with this line => this.state = { checked: false, checked2: true};
class Componente extends React.Component {
constructor(props) {
super(props);
this.state = { checked: false, checked2: true};
this.handleChange = this.handleChange.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked
})
}
handleChange2() {
this.setState({
checked2: !this.state.checked2
})
}
render() {
const togglecheck1 = this.state.checked ? 'hidden-check1' : '';
const togglecheck2 = this.state.checked2 ? 'hidden-check2' : '';
return <div>
<div>
<label>Check 1</label>
<input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
<label>Check 2</label>
<input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked2 } onChange={ this.handleChange2 } />
</div>
<div className={ togglecheck1 }>show hide div with check 1</div>
<div className={ togglecheck2 }>show hide div with check 2</div>
</div>;
}
}
ReactDOM.render(
<Componente />,
document.getElementById('container')
);
CSS
.hidden-check1 {
display: none;
}
.hidden-check2 {
visibility: hidden;
}
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
here's the codepen => http://codepen.io/parlop/pen/EKmaWM

In my case I felt that "defaultChecked" was not working properly with states/conditions. So I used "checked" with "onChange" for toggling the state.
Eg.
checked={this.state.enabled} onChange={this.setState({enabled : !this.state.enabled})}

If someone wants to handle dynamic data with multiple rows, this is for handing dynamic data.
You can check if the rowId is equal to 0.
If it is equal to 0, then you can set the state of the boolean value as true.
interface MyCellRendererState {
value: boolean;
}
constructor(props) {
super(props);
this.state = {
value: props.value ? props.value : false
};
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
}
handleCheckboxChange() {
this.setState({ value: !this.state.value });
};
render() {
const { value } = this.state;
const rowId = this.props.rowIndex
if (rowId === 0) {
this.state = {
value : true }
}
return (
<div onChange={this.handleCheckboxChange}>
<input
type="radio"
checked={this.state.value}
name="print"
/>
</div>
)
}

Don't make it too hard. First, understand a simple example given below. It will be clear to you. In this case, just after pressing the checkbox, we will grab the value from the state(initially it's false), change it to other value(initially it's true) & set the state accordingly. If the checkbox is pressed for the second time, it will do the same process again. Grabbing the value (now it's true), change it(to false) & then set the state accordingly(now it's false again. The code is shared below.
Part 1
state = {
verified: false
} // The verified state is now false
Part 2
verifiedChange = e => {
// e.preventDefault(); It's not needed
const { verified } = e.target;
this.setState({
verified: !this.state.verified // It will make the default state value(false) at Part 1 to true
});
};
Part 3
<form>
<input
type="checkbox"
name="verified"
id="verified"
onChange={this.verifiedChange} // Triggers the function in the Part 2
value={this.state.verified}
/>
<label for="verified">
<small>Verified</small>
</label>
</form>

<div className="display__lbl_input">
<input
type="checkbox"
onChange={this.handleChangeFilGasoil}
value="Filter Gasoil"
name="Filter Gasoil"
id=""
/>
<label htmlFor="">Filter Gasoil</label>
</div>
handleChangeFilGasoil = (e) => {
if(e.target.checked){
this.setState({
checkedBoxFG:e.target.value
})
console.log(this.state.checkedBoxFG)
}
else{
this.setState({
checkedBoxFG : ''
})
console.log(this.state.checkedBoxFG)
}
};

You can use a state var "enableSwitch" and a function "handleSwitch" to handle your default checked Switch:
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="switchId" checked={this.state.enableSwitch} onClick={this.handleSwitch}/>
<label class="custom-control-label" for="switchId">switch text</label>
</div>
Here's the function which inverts the variable if the user clicks on the switch:
handleSwitch = (e) => {
this.setState({ enableSwitch: !this.state.enableSwitch });
}
I know it's a late reply to an old question, but this short solution may help other users.

<div className="form-group">
<div className="checkbox">
<label><input type="checkbox" value="" onChange={this.handleInputChange.bind(this)} />Flagged</label>
<br />
<label><input type="checkbox" value="" />Un Flagged</label>
</div>
</div
handleInputChange(event){
console.log("event",event.target.checked) }
the Above handle give you the value of true or false upon checked or unChecked

I set the state as any[] type. and in the constructor set the state to null.
onServiceChange = (e) => {
const {value} = e.target;
const index = this.state.services.indexOf(value);
const services = this.state.services.filter(item => item !== value);
this.setState(prevState => ({
services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
}))
}
In the input element
this.onServiceChange(e)}/>
this.onServiceChange(e)}/>
this.onServiceChange(e)}/>
this.onServiceChange(e)}/>
I figured it out after some time. Thought it might help y'all :)

Related

remove the value enterd in input fild after submistion :react js [duplicate]

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.
<form id="create-course-form">
<input type="text" name="course_Name" ref="fieldName">
<input type="text" name="course_org" ref="fieldOrg">
<input type="text" name="course_Number" ref="fieldNum">
<input type="submit" name="saveCourse" value="Create">
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse}>
</form>
What I want is to empty all inputs when the cancel button is clicked. So far I've managed to do this by using each input's ref prop.
cancelCourse(){
this.refs.fieldName.value="";
this.refs.fieldorg.value="";
this.refs.fieldNum.value="";
}
However, I want to empty the input fields without having to empty each one seperately. I want something similar to this (jQuery): $('#create-course-form input[type=text]').val('');
The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks #Dan-Esparza for providing the links.
Also, please note that using string literals in ref is deprecated. Use the standard callback method instead.
Clearing a form with uncontrolled fields
You can clear the entire form rather than each form field individually.
cancelCourse = () => {
document.getElementById("create-course-form").reset();
}
render() {
return (
<form id="create-course-form">
<input />
<input />
...
<input />
</form>
);
}
If your form didn't have an id attribute you could use a ref as well:
cancelCourse = () => {
this.myFormRef.reset();
}
render() {
return (
<form ref={(el) => this.myFormRef = el;}>
<input />
<input />
...
<input />
</form>
);
}
Clearing a form with controlled fields
If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.
If they are declared individually, you need to reset each one explicitly:
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
...
inputVal_n: "",
});
}
render() {
return (
<input value={this.state.inputVal_1} onChange={this.handleInput1Change}>
<input value={this.state.inputVal_2} onChange={this.handleInput2Change}>
...
<input value={this.state.inputVal_n} onChange={this.handleInputnChange}>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
};
}
handleInput1Change = (e) => {
this.setState({inputVal_1: e.target.value});
}
handleInput2Change = (e) => {
this.setState({inputVal_2: e.target.value});
}
handleInput3Change = (e) => {
this.setState({inputVal_3: e.target.value});
}
handleInput4Change = (e) => {
this.setState({inputVal_4: e.target.value});
}
handleInput5Change = (e) => {
this.setState({inputVal_5: e.target.value});
}
handleInput6Change = (e) => {
this.setState({inputVal_6: e.target.value});
}
handleInput7Change = (e) => {
this.setState({inputVal_7: e.target.value});
}
handleInput8Change = (e) => {
this.setState({inputVal_8: e.target.value});
}
handleInput9Change = (e) => {
this.setState({inputVal_9: e.target.value});
}
handleInput10Change = (e) => {
this.setState({inputVal_10: e.target.value});
}
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
});
}
render() {
return (
<form>
<input value={this.state.inputVal_1} onChange={this.handleInput1Change} />
<input value={this.state.inputVal_2} onChange={this.handleInput2Change} />
<input value={this.state.inputVal_3} onChange={this.handleInput3Change} />
<input value={this.state.inputVal_4} onChange={this.handleInput4Change} />
<input value={this.state.inputVal_5} onChange={this.handleInput5Change} />
<input value={this.state.inputVal_6} onChange={this.handleInput6Change} />
<input value={this.state.inputVal_7} onChange={this.handleInput7Change} />
<input value={this.state.inputVal_8} onChange={this.handleInput8Change} />
<input value={this.state.inputVal_9} onChange={this.handleInput9Change} />
<input value={this.state.inputVal_10} onChange={this.handleInput10Change} />
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
There is a cleaner way to do this though. Rather than having n state properties and n event handlers, one for each input, with some clever coding we can reduce the code dramatically.
In the constructor we just declare an empty object, which will be used to hold input values. We use only one input handler and pass it the index of the input element we want to change the value of. This means that the value of an individual input is generated the moment we start typing into it.
To reset the form, we only need to set our input object back to being empty again.
The input value is this.state.inputVal[i]. If i doesn't exist (we haven't typed anything yet into that input) we want the value to be an empty string (instead of null).
cancelCourse = () => {
this.setState({inputVal: {}});
}
render() {
return (
<form>
{[...Array(n)].map(
(item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />
)}
</form>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal: {}
};
}
handleInputChange = (idx, {target}) => {
this.setState(({inputVal}) => {
inputVal[idx] = target.value;
return inputVal;
});
}
cancelCourse = () => {
this.setState({inputVal: {}});
}
render() {
return(
<form>
{[...Array(10)].map( //create an array with a length of 10
(item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} /> //bind the index to the input handler
)}
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Very easy:
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
// If using class component
<form onSubmit={this.handleSubmit.bind(this)}>
...
</form>
// If using function component
<form onSubmit={handleSubmit}>
...
</form>
Using event.target.reset() only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:
import React, { Component } from 'react'
class MyForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
placeholder="Enter name"
name="name"
value={name}
onChange={this.handleInputOnChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
ContactAdd.propTypes = {}
export default MyForm
You can also do it by targeting the current input, with anything.target.reset() . This is the most easiest way!
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
<form onSubmit={this.handleSubmit}>
...
</form>
Here's an update to Chris's answer above, using modern React hooks.
Same high level idea; your form can be either a Controlled or Uncontrolled component.
Uncontrolled components:
Uncontrolled components leave state management up to the browser. That means you have to ask the browser to reset the form inputs. To do that, capture the form element as a ref, and then call the submit() method on that element.
export default function Form() {
const ref = React.useRef();
function reset(ev) {
ev.preventDefault();
ref.current.reset();
}
return (
<form ref={ref}>
<label htmlFor="email">Email Address</label>
<input id="email" type="email" name="email" />
<label htmlFor="message">Message</label>
<textarea id="message" name="message" />
<button type="submit">Submit</button>
<button onClick={reset}>Reset</button>
</form>
);
}
Controlled components:
With a controlled component, you manage the state in React. That means you have to create the initial state, and update it every time an input changes. In this world, resetting the form is just a matter of setting the form state back to its initial state.
export default function Form() {
const [state, setState] = React.useState({ email: "", message: "" });
function reset(ev) {
ev.preventDefault();
setState({ email: "", message: "" });
}
return (
<form className="Form">
<label htmlFor="email">Email Address</label>
<input
id="email"
type="email"
name="email"
value={state.email}
onChange={(ev) => {
setState({ ...state, email: ev.target.value });
}}
/>
<label htmlFor="message">Message</label>
<textarea
id="message"
name="message"
value={state.message}
onChange={(ev) => {
setState({ ...state, message: ev.target.value });
}}
/>
<button type="submit">Submit</button>
<button onClick={reset}>Reset</button>
</form>
);
}
Full example at https://codesandbox.io/s/reactformreset-10cjn3
Following code should reset the form in one click.
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(e){
this.refs.form.reset();
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit} ref="form">
<input type="text" placeholder="First Name!" ref='firstName'/><br/<br/>
<input type="text" placeholder="Last Name!" ref='lastName'/><br/><br/>
<button type="submit" >submit</button>
</form>
</div>
}
}
To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :
// clear all your form
Object.keys(this.state).map((key, index) => {
this.setState({[key] : ""});
});
If your form is among other fields, you can simply insert them in a particular field of the state like that:
state={
form: {
name:"",
email:""}
}
// handle set in nested objects
handleChange = (e) =>{
e.preventDefault();
const newState = Object.assign({}, this.state);
newState.form[e.target.name] = e.target.value;
this.setState(newState);
}
// submit and clear state in nested object
onSubmit = (e) =>{
e.preventDefault();
var form = Object.assign({}, this.state.form);
Object.keys(form).map((key, index) => {
form[key] = "" ;
});
this.setState({form})
}
This one works best to reset the form.
import React, { Component } from 'react'
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state ///>>>>>>>>> note this one.
}
resetForm = () => {
this.setState(this.baseState) ///>>>>>>>>> note this one.
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val })
render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}
When the form is submitted, the 'event' will be passed as an argument to the handleSubmit method, and if that you can access the <form> element by typing event.target. then you just need to reset the form using .reset() form method.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
handleSubmit = (event)=>{
event.preventDefault()
....
event.target.reset()
}
render() {
return (
<>
<form onSubmit={this.handleSubmit}>
<label htmlFor='movieTitle'>Title</label>
<input name='movieTitle' id='movieTitle' type='text' />
<input type='submit' value='Find Movie Info' />
</form>
</>
)
}
I don't know if this is still relevant. But when I had similar issue this is how I resolved it.
Where you need to clear an uncontrolled form you simply do this after submission.
this.<ref-name-goes-here>.setState({value: ''});
Hope this helps.
import React, { Component } from 'react'
export default class Form extends Component {
constructor(props) {
super(props)
this.formRef = React.createRef()
this.state = {
email: '',
loading: false,
eror: null
}
}
reset = () => {
this.formRef.current.reset()
}
render() {
return (
<div>
<form>
<input type="email" name="" id=""/>
<button type="submit">Submit</button>
<button onClick={()=>this.reset()}>Reset</button>
</form>
</div>
)
}
}
/*
See newState and use of it in eventSubmit() for resetting all the state.
I have tested it is working for me. Please let me know for mistakes
*/
import React from 'react';
const newState = {
fullname: '',
email: ''
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
fullname: ' ',
email: ' '
}
this.eventChange = this
.eventChange
.bind(this);
this.eventSubmit = this
.eventSubmit
.bind(this);
}
eventChange(event) {
const target = event.target;
const value = target.type === 'checkbox'
? target.type
: target.value;
const name = target.name;
this.setState({[name]: value})
}
eventSubmit(event) {
alert(JSON.stringify(this.state))
event.preventDefault();
this.setState({...newState});
}
render() {
return (
<div className="container">
<form className="row mt-5" onSubmit={this.eventSubmit}>
<label className="col-md-12">
Full Name
<input
type="text"
name="fullname"
id="fullname"
value={this.state.fullname}
onChange={this.eventChange}/>
</label>
<label className="col-md-12">
email
<input
type="text"
name="email"
id="email"
value={this.state.value}
onChange={this.eventChange}/>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
)
}
}
export default Form;
the easiest way is doing it regularly with just HTML and using the button type "reset" there is no need to mess with anything in react at all, no state, no nothing.
import React, {useState} from 'react'
function HowReactWorks() {
return (
<div>
<form>
<div>
<label for="name">Name</label>
<input type="text" id="name" placeholder="name" />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" placeholder="password" />
</div>
<button type="reset">Reset</button>
<button>Submit</button>
</form>
</div>
)
}
export default HowReactWorks
edited for the people that don't know how to include HTML in react
You can use this method as well
const resetData = (e) => {
e.preventDefault();
settitle("");
setdate("");
};
<input type="text" onChange={(e) => settitle(e.target.value)} value={title} />
<input type="date" onChange={(e) => setdate(e.target.value)} value={date} />
<button onClick={resetData}>Reset Data</button>
This is the solution that worked for me, in the case of parent component triggering reset of child controlled input components:
const ParentComponent = () => {
const [reset, setReset] = useState()
const submitHandler = (e) => {
e.preventDefault()
//do your stuff
setReset(Date.now()) // pass some value to trigger update
}
return (
<form onSubmit={submitHandler}>
<ChildInputComponent reset={reset} />
<ChildInputComponent reset={reset} />
</form>
)
}
const ChildInputComponent = ({reset}) => {
const [value, setValue] = useState()
useEffect(() => {
setValue('')
}, [reset])
return <input value={value} onChange={(e) => setValue(e.target.value)} />
}
Assuming you declared
const [inputs, setInputs] = useState([]);
As multiple parameters. You can actually reset the items using this syntax:
setInputs([]);
Just in case, this how you define handleChange.
You can use this form or any ways you want.
const handleChange = (event) => {
const name = event.target.name;
const email = event.target.email;
const message = event.target.message;
const value = event.target.value;
setInputs(values => ({...values, [name]: value, [email]: value, [message]: value}))
}
You can use this form as an example.
<form onSubmit={handleSubmit}>
<div className="fields">
<div className="field half">
<label for="name">Name</label>
<input value={inputs.name || ''} type="text" name="name" id="nameId" onChange={handleChange} maxLength="30" />
</div>
<div className="field half">
<label for="email">Email</label>
<input value={inputs.email || ''} type="text" name="email" id="emailId" onChange={handleChange} maxLength="40"/>
</div>
<div className="field">
<label for="message">Message</label>
<textarea value={inputs.message || ''} name="message" id="messageId" rows="6" onChange={handleChange} maxLength="400" />
</div>
</div>
<ul className="actions">
<li><input type="submit" value="Send Message" className="primary" /></li>
<li><input onClick={resetDetails} type="reset" value="Clear" /></li>
</ul>
</form>
This is just one of many ways to declare forms. Good luck!
const onReset = () => {
form.resetFields();
};
state={
name:"",
email:""
}
handalSubmit = () => {
after api call
let resetFrom = {}
fetch('url')
.then(function(response) {
if(response.success){
resetFrom{
name:"",
email:""
}
}
})
this.setState({...resetFrom})
}
Why not use HTML-controlled items such as <input type="reset">

How to fetch input from text box and print in React?

I am new to React trying to write a very simple project that fetches input of both text boxes and when button is clicked, the 'data' in text boxes is printed on paragraph.
How do I fetch text's in input text boxes when button is clicked?
class Input extends Component {
state = {
tagged: false,
message: '',
}
handleClick(e) {
this.setState({tagged: true});
e.preventDefault();
console.log('The link was clicked.');
}
render() {
return (
<div id="id" style={divStyle}>
<p> hello </p>
<input
style = {textStyle}
placeholder="user#email.com"
type="text">
</input>
<input
style = {textStyle}
placeholder="tag"
type="text">
</input>
<button
onClick={(e) => this.handleClick(e)}
style={buttonStyle}>
{this.state.tagged ? 'Tagged' : 'Tag ' }
</button>
<p>
{this.state.tagged ? 'Clicked' : 'Still' }
</p>
</div>
)
}
}
You can add onChange event handler in each input.
class Input extends Component {
state = {
tagged: false,
message: '',
input1: '',
input2: '',
}
handleClick(e) {
// access input values in the state
console.log(this.state) // {tagged: true, input1: 'text', input2: 'text2'}
this.setState({tagged: true});
e.preventDefault();
console.log('The link was clicked.');
}
handleInputChange = (e, name) => {
this.setState({
[name]: e.target.value
})
}
render() {
return (
<div id="id" style={divStyle}>
<p> hello </p>
<input
style = {textStyle}
placeholder="user#email.com"
type="text"
onChange={(e) => this.handleInputChange(e, 'input1')}
>
</input>
<input
style = {textStyle}
placeholder="tag"
type="text"
onChange={(e) => this.handleInputChange(e, 'input2')}
>
</input>
<button
onClick={(e) => this.handleClick(e)}
style={buttonStyle}>
{this.state.tagged ? 'Tagged' : 'Tag ' }
</button>
<p>
{this.state.tagged ? 'Clicked' : 'Still' }
</p>
</div>
)
}
}
There are two different ways of working with react inputs - you can either make them controlled or uncontrolled. When you say fetch text from inputs, this is called uncontrolled components and means that form data is handled by the DOM itself and not by react.
This is achieved by using ref and literally getting a reference to your input and fetching its value when you need it. you can read more about this approach in react docs.
According to react docs, it is recommended using controlled components
In most cases, we recommend using controlled
components to implement forms. In a controlled
component, form data is handled by a React component.
This means that you don’t use references to the inputs and instead handle changes of your inputs with an event handler and update state with the new values that the user has entered into the input fields. According to react docs here is how react handles form with controlled components:
the React component that
renders a form also controls what happens in that form on subsequent
user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
In your case you can do this if you choose controlled inputs:
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
tagged: false,
firstInput: '',
secondInput: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleClick(e) {
this.setState({ tagged: true });
e.preventDefault();
console.log('The link was clicked.');
}
render() {
const { firstInput, secondInput, tagged } = this.state;
return (
<div id="id">
{tagged && <p>{firstInput} {secondInput}</p> }
<input
value={firstInput}
name="firstInput"
onChange={this.handleChange}
type="text" />
<input
value={secondInput}
name="secondInput"
onChange={this.handleChange}
type="text" />
<button onClick={(e) => this.handleClick(e)}>
{tagged ? 'Tagged' : 'Tag '}
</button>
</div>
)
}
}
Here you put the inputs' values on state and update state when the user writes something in your inputs. If you however want to use uncontrolled components you can do it this way:
class UncontrolledInput extends React.Component {
state = {
tagged: false,
message: '',
}
handleClick(e) {
e.preventDefault();
const messageFromInputs = `${this.firstInput.value} ${this.secondInput.value}`;
this.setState({ tagged: true, message: messageFromInputs });
}
render() {
return (
<div id="id">
<p>{this.state.message}</p>
<input ref={(input) => this.firstInput = input} type="text" />
<input ref={(input) => this.secondInput = input} type="text" />
<button onClick={(e) => this.handleClick(e)}>
{this.state.tagged ? 'Tagged' : 'Tag '}
</button>
<p>
{this.state.tagged ? 'Clicked' : 'Still'}
</p>
</div>
)
}
}
Here you will actually fetch values from your inputs when the button is clicked.
I made a working example with both ways on codesandbox.

Setting checkbox with click of another element - react

What I am trying to do here is set the value of the checkbox to 'checked' (because it is styled as a slider) when I click on the <i className='icon-gear'. I'm having trouble accessing input to change it's state. Am I missing something here or am I going about it the wrong way/what would be the better way to approach it? Thanks ahead of time for the help!
const Slider = () => {
return (
<div className="slider-container">
<label className="switch">
<input type="checkbox" />
<span className="slider round" />
</label>
<p className="batch-slider-title"> Batch Widget </p>
</div>
);
};
class Settings extends Component {
constructor() {
super();
this.state = {
isWidgetDisplayed: false,
checked: false,
};
this.showWidget = this.showWidget.bind(this);
}
showWidget() {
this.setState({
isWidgetDisplayed: !this.state.isWidgetDisplayed,
checked: !this.state.checked,
});
}
mouseOut() {
this.setState({showing: false});
}
mouseOver() {
this.setState({showing: true});
}
render() {
const batchWidget = this.state.isWidgetDisplayed ? <BatchWidget /> : null;
const slider = showing => {
if (showing === true) {
return <Slider />;
}
return null;
};
return (
<div>
<div className="settings">
<i className="icon-gear" onMouseOut={() => this.mouseOut()} onMouseOver={() => this.mouseOver()} onClick={this.showWidget} />
</div>
{slider(this.state.showing)}
{batchWidget}
</div>
);
}
}
<input type="checkbox" /> should be <input type="checkbox" checked={this.props.checked}/>
And it should receive those props via <Slider checked={this.state.checked}/>

React setState and update() addon

I'm a beginer using ReactJS and today I had a situation that I don't know how to be explain.
I'm working on a project with a similar situation as described bellow:
var update = React.addons.update;
class HelloWidget extends React.Component{
constructor(props) {
super(props);
this.state = {
group1: 'show',
group2: 'A'
};
this.Update = this.Update.bind(this);
this.handleChange1 = this.handleChange1.bind(this);
}
Update(e, value = ''){
let field = e;
if(!value) field = e.target.name
//this solution work
/*this.setState({
[field]: value || e.target.value
});*/
//this solution doesn't work
let theState = Object.assign({}, this.state),
updatedState = update(theState,{[field]: {$set: value || e.target.value}})
console.log("UPDATE RESULTS");console.log(updatedState);
this.setState(updatedState);
}
handleChange1(e) {
const filters = this.state
if(filters.group1 === 'show' && filters.group2 === 'C' ){
this.Update('group2', 'A');
}
this.Update(e);
}
render() {
const filters = this.state;
console.log("RENDER");console.log(filters);
return (
<div className="widget">
<div>
Group 1<br />
<input type="radio" value="show" name="group1" defaultChecked={filters.group1 === 'show'} onChange={this.handleChange1} /> Show All Group 2
<input type="radio" value="hide" name="group1" defaultChecked={filters.group1 === 'hide'} onChange={this.handleChange1} /> Hide 3rd option
</div>
<br /><br />
<div>
Group 2<br />
<input type="radio" value="A" name="group2" checked={filters.group2 === 'A'} onChange={this.Update} /> A
<input type="radio" value="B" name="group2" checked={filters.group2 === 'B'} onChange={this.Update} /> B
{filters.group1 === 'show' && <label><input type="radio" value="C" name="group2" checked={filters.group2 === 'C'} onChange={this.Update} /> C</label>}
</div>
</div>
);
}
}
ReactDOM.render(<HelloWidget />, document.getElementById('container'));
.widget {
width: 402px;
margin:10px auto;
padding:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Shortly, I have a function that update state from different children Components. According attached source code, changing options in first radio group should show or hide an option (last) on second radio group. If the hidden option is checked then default (first) option should been checked after hide.
Everything works fine when I use setState() directly, but because of state object complexity, I used update() addon and the result is not the same - default option on second radio group is not checked after last is hidden.
Where is my issue using update()?
Thanks
Seems that the issue is what is sent to update: for working solution - just one field, using update() - entire state object.
If I will change the working part to :
let theState = Object.assign({}, this.state),
updatedState = Object.assign({}, theState, {
[field]: value || e.target.value
})
;
this.setState(updatedState);
then I will receive the same issue.

React Checkbox not sending onChange

TLDR: Use defaultChecked instead of checked, working jsbin.
Trying to setup a simple checkbox that will cross out its label text when it is checked. For some reason handleChange is not getting fired when I use the component. Can anyone explain what I'm doing wrong?
var CrossoutCheckbox = React.createClass({
getInitialState: function () {
return {
complete: (!!this.props.complete) || false
};
},
handleChange: function(){
console.log('handleChange', this.refs.complete.checked); // Never gets logged
this.setState({
complete: this.refs.complete.checked
});
},
render: function(){
var labelStyle={
'text-decoration': this.state.complete?'line-through':''
};
return (
<span>
<label style={labelStyle}>
<input
type="checkbox"
checked={this.state.complete}
ref="complete"
onChange={this.handleChange}
/>
{this.props.text}
</label>
</span>
);
}
});
Usage:
React.renderComponent(CrossoutCheckbox({text: "Text Text", complete: false}), mountNode);
Solution:
Using checked doesn't let the underlying value change (apparently) and thus doesn't call the onChange handler. Switching to defaultChecked seems to fix this:
var CrossoutCheckbox = React.createClass({
getInitialState: function () {
return {
complete: (!!this.props.complete) || false
};
},
handleChange: function(){
this.setState({
complete: !this.state.complete
});
},
render: function(){
var labelStyle={
'text-decoration': this.state.complete?'line-through':''
};
return (
<span>
<label style={labelStyle}>
<input
type="checkbox"
defaultChecked={this.state.complete}
ref="complete"
onChange={this.handleChange}
/>
{this.props.text}
</label>
</span>
);
}
});
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange method:
event.target.checked
It's better not to use refs in such cases. Use:
<input
type="checkbox"
checked={this.state.active}
onClick={this.handleClick}
/>
There are some options:
checked vs defaultChecked
The former would respond to both state changes and clicks.
The latter would ignore state changes.
onClick vs onChange
The former would always trigger on clicks.
The latter would not trigger on clicks if checked attribute is present on input element.
If you have a handleChange function that looks like this:
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
}
You can create a custom onChange function so that it acts like an text input would:
<input
type="checkbox"
name="check"
checked={this.state.check}
onChange={(e) => {
this.handleChange({
target: {
name: e.target.name,
value: e.target.checked,
},
});
}}
/>
In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick property as an alternative. The defaultChecked, the condition may leave a fixed state for v16 IINM.
class CrossOutCheckbox extends Component {
constructor(init){
super(init);
this.handleChange = this.handleChange.bind(this);
}
handleChange({target}){
if (target.checked){
target.removeAttribute('checked');
target.parentNode.style.textDecoration = "";
} else {
target.setAttribute('checked', true);
target.parentNode.style.textDecoration = "line-through";
}
}
render(){
return (
<span>
<label style={{textDecoration: this.props.complete?"line-through":""}}>
<input type="checkbox"
onClick={this.handleChange}
defaultChecked={this.props.complete}
/>
</label>
{this.props.text}
</span>
)
}
}
I hope this helps someone in the future.
In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):
this.handleInputChange = (e) => {
item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
}
onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.
<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;
In material ui, state of checkbox can be fetched as
this.refs.complete.state.switched

Resources