score:58
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
score:-2
<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
score:-2
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 :)
score:0
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>
score:0
<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)
}
};
score:0
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.
score:1
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
score:1
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})}
score:1
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>
)
}
score:3
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>
)
}
}
score:5
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 })}
score:5
Value would be whether true or false defaultChecked={true}
<input type="checkbox"
defaultChecked={true}
onChange={() => setChecked(!checked)}
/>
score:6
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>
score:6
import React, { useState } from 'react'
const [rememberUser, setRememberUser] = useState(true) //use false for unchecked initially
<input
type="checkbox"
checked={rememberUser}
onChange={() => {
setRememberUser(!rememberUser)
}}
/>
score:13
in addition to the correct answer you can just do :P
<input name="remember" type="checkbox" defaultChecked/>
score:38
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
score:150
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.
score:310
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} />
Source: stackoverflow.com
Related Query
- How to set default Checked in checkbox ReactJS?
- How to handle checkbox checked status in reactJS
- ReactJS + Material-UI: How to set current date as default value using Material-UI's <DatePicker>?
- How to Set radio button default checked in react?
- CSS: How to set url image properly to checked checkbox
- How can I set the default state of a checkbox based on value in firestore in react table
- How to set checkbox component checked in Material-UI React?
- How to set value for the checkbox in ReactJS
- How to set Material UI checkbox list checked by default?
- How to set default state in checkbox when it is not checked- React
- How to set the value of a checkbox inside a form in reactjs
- How do i set sate based on the condition in checkbox Change function reactjs
- How to set default value in checkbox and radio button?
- How to select default checkbox as selected in reactjs
- How to set up default value if props is empty? Using reactJS
- How to set all checkboxes checked by default if dropdown is closed?
- How can I set default checked in Ag-Grid React.js?
- how do we push a checkbox to an array while checkbox is by default checked in react js?
- How to set component default props on React component
- How to set a default value in react-select
- reactjs - how to set inline style of backgroundcolor?
- How to set default value in material-UI select box in react?
- How to make default checked for radio buttons in react?
- ReactJS - How can I set a value for textfield from material-ui?
- React.js - How to set a default value for input date type
- How to set React default props for object type
- How can I set default sorter and filters on antd table components?
- How to properly set axios default headers
- How do I use React and forms to get an array of checked checkbox values?
- How to properly set default values using redux-forms?
More Query from same tag
- How do I go back to home page if previous path don't exists react router v6
- react with JSS - how to add class to child component?
- How to access collections in Firebase Firestore
- Sequential NPM script after "react-scripts start"
- I can't pass parameters to external function to render the message, TypeError: Class constructor AlertMessage cannot be invoked without 'new'
- Status does not change when I delete data from here
- Navigate to the URL without react-router - "_this.props.history is undefined" error
- ReactJS: How to redirect from one route to another in react-router after XHR?
- How can I wrap the Children of a Parent component in a HOC and render them in React?
- Accessing Jenkins API using Javascript
- How to test method call times in react connected componentDidMount
- Unable to use the spread operator after ejecting create-react-app
- React - Use nested map functions in render function to create a 2D board/grid
- How implementing a modal with reactjs
- Icon should have `type` prop or `component` prop or `children`?
- Material Grid refused to lay out horizontal even it's default behavior
- React Dynamically download Components and get data from all child components
- React & Mobx: render (via method render()) @observable data that will be modified after the specified component is rendered
- React How can open/close Model in class component
- Is there any way to validate each column of ANT DESIGN Table indiviually?
- Delete multiple items in one array in react state from another array
- Popover does not show up in React
- Dynamic CSS stylesheets based using State Values in React
- Unable to use custom palette for mui component
- How to use apollo-link-http with apollo-upload-client?
- Medium.js in React.js component using invokeElement
- Picking correct enum type to access object nested property
- Adding values to a state array in React
- The values iterated by .map() do not reflect inside the function in html attribute
- Download document on the same page when using antd upload