Setting checkbox with click of another element - react - reactjs

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}/>

Related

Render html based on the radio select

I have two radio buttons and need to render a different form for each when the user click the continue button, how can I do this? Here's the code I have so far.
class App extends Component {
constructor() {
super();
this.state = {
name: "typeOfInternet"
};
this.onChangeValue = this.onChangeValue.bind(this);
}
onChangeValue(event) {
console.log(event.target.value);
}
handleChange = () =>
this.setState({ showComponent: !this.state.showComponent });
render() {
return (
<Container>
<section className="section">
<div className="tittle">
<span>
Vamos começar? Escolha a modalidade e preencha seus dados para
continuar.
</span>
</div>
<div className="check-block" onChange={this.onChangeValue}>
<div className="check">
<input
type="radio"
id="residencia"
name="internet"
value="residencial"
/>
<label for="residencial">Internet Residencial</label>
</div>
<div className="check">
<input
type="radio"
id="empresa"
name="internet"
value="empresarial"
/>
<label for="empresarial">Internet Empresarial</label>
</div>
</div>
<div className="continue">
<button
className="btn-continue"
>
Continue
</button>
</div>
</section>
</Container>
)
}
}
export default App ;
The difference between codes are some input fields that "imternet Empresarial" has and "Internet Residencial" does not
There is no need for onChangeValue function because you're not calling it anywhere instead you can attach handleChange function to the <input> tags.
You should use the name which is provided in <input> inside state. So that it will be easier to use in setState.
There's no need to use .bind() also, with the help of arrow functions => you can escape that.
Inside switch, on different cases of the values instead of using <div>...</div>, you can call different components present in separate file. (in order to make the component readable)
Codesandbox Demo
import { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
internet: ""
};
}
handleChange = (e) => this.setState({ [e.target.name]: e.target.value });
renderForm = () => {
switch (this.state.internet) {
case "residencial":
return (
<div>
<h1>residencial form</h1>
</div>
);
case "empresarial":
return (
<div>
<h1>empresarial form</h1>
</div>
);
default:
return null;
}
};
render() {
return (
<section className="section">
<div className="tittle">
<span>
Vamos começar? Escolha a modalidade e preencha seus dados para
continuar.
</span>
</div>
<div className="check-block" onChange={this.onChangeValue}>
<div className="check">
<input
type="radio"
id="residencia"
name="internet"
value="residencial"
onChange={this.handleChange}
/>
<label htmlFor="residencial">Internet Residencial</label>
</div>
<div className="check">
<input
type="radio"
id="empresa"
name="internet"
value="empresarial"
onChange={this.handleChange}
/>
<label htmlFor="empresarial">Internet Empresarial</label>
</div>
</div>
{this.renderForm()}
<div className="continue">
<button className="btn-continue">Continue</button>
</div>
</section>
);
}
}
export default App;
First, you need to create your form element to render when radio buttons get toggled. Something like this:
const Form = ({ type }) => {
return type === "residencial" ? <div>Form 1</div> : <div>Form 2</div>;
};
Then keep track of the currently checked radio button and whether or not the continue button has been pressed. Something like this would work (Sandbox):
const Form = ({ type }) => {
return type === "residencial" ? <div>Form 1</div> : <div>Form 2</div>;
};
class App extends Component {
constructor() {
super();
this.state = {
name: "",
step: 1
};
}
onChangeValue = (event) => {
console.log(event.target.value);
this.setState({ name: event.target.value });
};
handleContinue = () => {
this.setState({ step: 2 });
};
render() {
const { step, name } = this.state;
return (
<div>
<section className="section">
<div className="tittle">
<span>
Vamos começar? Escolha a modalidade e preencha seus dados para
continuar.
</span>
</div>
<div className="check-block">
<div className="check">
<input
type="radio"
id="residencia"
name="internet"
value="residencial"
onChange={this.onChangeValue}
/>
<label for="residencial">Internet Residencial</label>
</div>
<div className="check">
<input
type="radio"
id="empresa"
name="internet"
value="empresarial"
onChange={this.onChangeValue}
/>
<label for="empresarial">Internet Empresarial</label>
</div>
</div>
<div className="continue">
<button
disabled={name === ""}
className="btn-continue"
onClick={this.handleContinue}
>
Continue
</button>
<hr />
{step === 2 ? <Form type={name} /> : null}
</div>
</section>
</div>
);
}
}
export default App;
There is also no need to bind your class functions, just use arrow functions, they will make your life much easier.

Can't get Materialize Picker to work in React

I am new to React and can't seem to get my Materialize Picker to work at all.
I have all the Materialize installed and imported.
It displays correctly and opens correctly but when I select a date, I get an error displaying every time and can't figure out why.
TypeError: Cannot read property 'completeBy' of undefined
I have added all my code below for my test page where it's currently sitting.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addToDo } from '../../store/actions/todoActions';
import { Redirect } from 'react-router-dom';
import M from "materialize-css";
//import moment from 'moment';
class AddToDo extends Component {
state = {
title: '',
content: '',
assignTo: '',
completeBy: new Date(),
format: 'ddd d, mmm',
//formatMoment: 'ddd D, MMM'
}
handleChange = (e) => {
this.setState({
[e.target.id]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.addToDo(this.state);
this.props.history.push('/');
}
handleCancel = (e) => {
e.preventDefault();
this.props.history.push('/');
}
canBeSubmitted() {
const { title, content, assignTo } = this.state;
return title.length > 0 && content.length > 0 && assignTo.length > 0;
}
componentDidMount() {
let selects = document.querySelectorAll('select');
let elems = document.querySelectorAll('.datepicker');
M.Datepicker.init(elems, {
defaultDate: new Date(),
format: this.state.format,
container: 'body',
onSelect: function(date) {
this.setState({ completeBy: this.state.completeBy }); // Errors here
},
autoClose: true
});
M.FormSelect.init(selects, {});
}
render() {
const { auth } = this.props;
const isEnabled = this.canBeSubmitted();
if (!auth.uid) {
return <Redirect to='/login' />
}
return (
<div className="container">
<form className="white" onSubmit={ this.handleSubmit }>
<h5 className="grey-text text-darken-3">Add a new todo item</h5>
<div className="input-field">
<input type="text" id='title' onChange={ this.handleChange } autoFocus />
<label htmlFor="title">Todo title <span className="red-text">*</span></label>
</div>
<div className="input-field">
<textarea id="content" className="materialize-textarea" onChange={ this.handleChange }></textarea>
<label htmlFor="content">Todo content <span className="red-text">*</span></label>
</div>
<div className="input-field">
<select id="assignTo" onChange={ this.handleChange }>
<option value="default" disabled selected>Please select</option>
<option value="Kyle">Kyle</option>
<option value="Mike">Mike</option>
<option value="Tony">Tony</option>
</select>
<label htmlFor="assignTo">Assign todo to <span className="red-text">*</span></label>
</div>
<div className="input-field">
<label htmlFor="completeBy">To be completed by</label>
<input
id="completeBy"
type="text"
className="datepicker dateset"
// defaultValue={ moment(this.state.completeBy).format(
// this.state.formatMoment
// )}
/>
</div>
<div className="row">
<div className="col s12 l1">
<button className="btn pink lighten-1 col s12" disabled={!isEnabled}>Add</button>
</div>
<div className="col s12 l1">
<button onClick={this.handleCancel} className="btn yellow darken-2 col s12">Cancel</button>
</div>
</div>
</form>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return {
addToDo: (todo) => dispatch(addToDo(todo))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AddToDo)
Some may recognise the code base as I was following Net Ninja tutorials but adding to it for my learning. I have also had a look at the following stack question and tried their solution as its the same code as mine also but it does not work for me.
I have checked my package.json and I am using "materialize-css": "^1.0.0-rc.2" and I am not using react-materialize.
Screenshots
Initial load
Click in the date field
Set a date, picker closes and get
Most of the time I use arrow functions when I define callbacks. Because it handles the scope of this differently than a function. Try to replace onSelect callback to an arrow function:
M.Datepicker.init(elems, {
defaultDate: new Date(),
format: this.state.format,
container: 'body',
onSelect: (date) => {
this.setState({ completeBy: this.state.completeBy });
},
autoClose: true
});

ReactJs: Defaultvalue of textArea not updated

I'm working on a form in my ReactJs app. What I'd like to do:
1/ select a draft letter from an array of draft letters by its id // ok
2/ display the title, body and location of the selected draft letter in a form below // ok
3/ then the user should be able to edit all the fields // not ok!
This is what I did :
class NewLetter extends Component {
constructor(props) {
super(props)
this.state = {
city: "",
title: "",
letterBody: "",
}
this.handleChange_city = this.handleChange_city.bind(this);
this.handleChange_letterBody = this.handleChange_letterBody.bind(this);
this.handleChange_title = this.handleChange_title.bind(this);
}
handleChange_city(e) {
this.setState({
city: e.target.value
});
}
handleChange_letterBody(e) {
this.setState({
title: e.target.value
});
}
handleChange_title(e) {
this.setState({
letterBody: e.target.value
});
}
render() {
return (
<form className="containerLetter">
<div className="form-group">
<input type="text" className="form-control" id="letterLocation" placeholder="where are you?" value={this.props.city} onChange={this.handleChange_city}/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="letterTitle" placeholder="give a title to your letter" value={this.props.title} onChange={this.handleChange_title} />
</div>
<div className="form-group">
<textarea type="text" className="form-control" id="letterBody" placeholder="Letter content" value={this.props.letterBody} onChange={this.handleChange_letterBody} />
</div>
<button className="actionButton">Send the letter</button> <br />
<button className="actionButton">Save as draft</button>
</form>
)
}
}
export default NewLetter
If I use value, the fields are not editable
If I use defaultValue the field are editable but when the defaultValue change, React doesn't re-render. The values are passed as props by the parent component:
class DraftLetters extends Component {
constructor(props) {
super(props)
this.state = {
selectedDraftIndex: 0,
};
this.handleChange = this.handleChange.bind(this);
}
getListOfDrafts = () => {
var list = []
for (let i = 0; i < this.props.drafts.length; i++) {
list.push(<option value={i}> {this.props.drafts[i].redactionDate} </option>);
}
return (list);
}
handleChange(e) {
this.setState({
selectedDraftIndex: e.target.value,
})
}
render() {
return (
<div >
{(this.props.drafts.length != 0) &&
<div className="form-group selectLetter">
<label for="sel1">Select the draft:</label>
<select onChange={this.handleChange} className="form-control" id="sel1">
{this.getListOfDrafts()}
</select>
</div>
}
{(this.props.drafts.length == 0) &&
<div className="form-group">
<p className="noLetter"> You haven't saved any draft.</p>
<img width="400px" className="img-fluid" src={painting} alt="tableau"></img>
</div>
}
<div>
<br />
{(this.props.drafts.length != 0) &&
<NewLetter city={this.props.drafts[this.state.selectedDraftIndex].city}
title={this.props.drafts[this.state.selectedDraftIndex].title}
letterBody={this.props.drafts[this.state.selectedDraftIndex].letterBody}></NewLetter>
}
{this.state.selectedDraftIndex}
</div>
</div>
)
}
}
export default DraftLetters
It seems to be a well known problem
This is what I found:
defaultValue change does not re-render input
React input defaultValue doesn't update with state
https://github.com/facebook/react/issues/4101
Is there nowdays a fix for this problem?

Cannot able to Access Data passed as argument from one component to another in ReactJs

In my scenario, I have two components ListEnterprise and AddEnterprise. On clicking the update button I need to access and send the particular Id of Enterprise to AddEnterprise(we are using same component for adding and updating the records). How to access the EnterpriseId in AddEnterprise component? Thanks in advance.
ListEnterprise
class ListEnterprises extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
enterprises: [],
message: null,
showFormMessage: false,
showUpdateForm: false,
}
//Any method in a react component should be bound to this
this.refreshEnterprises = this.refreshEnterprises.bind(this);
this.editEnterprise = this.editEnterprise.bind(this);
}
// After all the elements of the page is rendered correctly, this method is called.
// After the markup is set on the page, this technique called by React itself to either fetch the data from An External API or perform some unique operations which need the JSX.API
// componentDidMount() method is the perfect place, where we can call the setState() method to change the state of our application and render() the updated data loaded JSX. For example, we are going to fetch any data from an API then API call should be placed in this lifecycle method,
// and then we get the response, we can call the setState() method and render the element with updated data.
//React defines a component lifecycle. componentDidMount will be called as soon as the component is mounted. We are calling refreshCourses as soon as a component is mounted.
componentDidMount() {
this.refreshEnterprises();
}
_showMessage = (bool, update = false) => {
this.setState({
showFormMessage: bool,
showUpdateForm: false,
});
if (update) {
this.refreshEnterprises();
}
}
refreshEnterprises() {
EnterpriseService.retrieveAllEnterprises()
.then((response) => {
console.log(response.data);
this.setState({ enterprises: response.data, isLoading: false });
}).catch((error) => {
console.log(error);
});
}
// removeEnterprise(id) {
// EnterpriseService.deleteEnterprise(id)
// .then((response) => {
// console.log(response.data);
// let updatedEnterprises = [...this.state.enterprises].filter(i => i.id !== id);
// this.setState({ enterprises: updatedEnterprises });
// }).catch((error) => {
// console.log(error);
// });
// }
editEnterprise(enterpriseId) {
this._showMessage.bind(null, false);
this.setState({ showUpdateForm: true, showFormMessage: false });
return enterpriseId;
}
render() {
console.log("Rendering Enterprises");
if (this.state.showUpdateForm)
let recordId = this.editEnterprise;
if (this.state.isLoading)
return (<div>Loading...</div>);
return (
<div key={this.props.location.pathname}>
<NavigationComponent /><br /><br />
<h3 align="center">Here are all your Enterprises</h3><br />
{this.state.message && <div class="alert alert-success">{this.state.message}</div>}
<Container>
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>Enterprise</th>
<th>Industry</th>
<th>Business Units</th>
<th>Description</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{
this.state.enterprises.map(
enterprise =>
<tr key={enterprise.id}>
<td>{enterprise.enterpriseName}</td>
<td>{enterprise.industry}</td>
<td>
{enterprise.businessUnits.map(bu =>
<td>{bu.businessUnitName}</td>
)}
</td>
<td>{enterprise.description}</td>
<td><button className="btn btn-warning" onClick={() => this.editEnterprise(enterprise.id)}>Update</button></td>
<td><button className="btn btn-danger" onClick={() => this.removeEnterprise(enterprise.id)}>Delete</button></td>
</tr>
)
}
</tbody>
</Table>
</Container>{" "}{" "}{" "}
<div className="container">
<Button color="primary" size="lg" onClick={this._showMessage.bind(null, true)}>Add Enterprise</Button>{' '}
<Button color="secondary" size="lg" onClick={this._showMessage.bind(null, false)}>Hide</Button>{' '}
{(this.state.showFormMessage && <AddEnterprise showMessage={this._showMessage} {...this.props} />)}
{(this.state.showUpdateForm && <AddEnterprise editEnterprise={this.editEnterprise} showUpdateForm={this.state.showUpdateForm} showMessage={this._showMessage} {...this.props} />)}
</div>
<br /><br />
<FooterComponent />
</div >
);
}
}
export default ListEnterprises;
AddEnterprise(Same component is Using to Update as well)
class AddEnterprise extends Component {
emptyEnterprise = {
enterpriseName: "",
industry: "",
description: "",
businessUnits: ""
};
constructor(props) {
super(props);
this.state = {
isLoading: true,
isForm: false,
enterprisePayload: this.emptyEnterprise
}
this.handleChange = this.handleChange.bind(this);
this.addEnterprise = this.addEnterprise.bind(this);
this.editEnterprise = this.editEnterprise.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
let updatedEnterprisePayload = { ...this.state.enterprisePayload };
updatedEnterprisePayload[name] = value;
this.setState({ enterprisePayload: updatedEnterprisePayload });
console.log(updatedEnterprisePayload);
}
editEnterprise() {
this.props.editEnterprise();
}
addEnterprise(event) {
var obj = [];
const businessUnitsData = this.state.enterprisePayload.businessUnits.split(",");
console.log(businessUnitsData);
businessUnitsData.map(x => {
let objVar = new BusinessUnit("", x);
console.log(objVar);
obj.push(objVar);
});
console.log(obj);
let updatedPayload = this.state.enterprisePayload;
updatedPayload["businessUnits"] = obj;
this.setState({ enterprisePayload: updatedPayload });
const payload = this.state.enterprisePayload;
EnterpriseService.addEnterprise(payload)
.then((response) => {
this.setState({ isLoading: false, isForm: true });
this.props.showMessage(false, true); //In React we use state for things like these, you can't always redirect
})
.catch((error) => {
console.log(error);
});
}
render() {
if (this.state.isLoading && this.state.isForm)
return (<div>Loading...</div>);
return (
<div className="base-container">
{!this.props.showUpdateForm && <div className="header"><div><br />Add Enterprise</div></div>}
{this.props.showUpdateForm && <div className="header"><div><br />Update Enterprise</div></div>}
<div className="content">
<div className="form">
<div className="form-group">
<label htmlFor="enterpriseName" for="enterpriseName">Enterprise Name</label>
<input type="text" name="enterpriseName" id="enterpriseName" placeholder="enterpriseName" onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="industry" for="industry">Industry</label>
<input type="text" name="industry" id="industry" placeholder="industry" onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="businessUnits" for="businessUnits">Business Units</label>
<input type="text" name="businessUnits" id="businessUnits" placeholder="businessUnits" onChange={this.handleChange} />
</div>
<div className="form-group">
<label htmlFor="description" for="description">Description</label>
<input type="text" name="description" id="description" placeholder="description" onChange={this.handleChange} />
</div>
</div>
</div>
<div className="footer">
{!this.props.showUpdateForm && <button type="button" className="btn" onClick={this.addEnterprise}>Add</button>}
{this.props.showUpdateForm && <button type="button" className="btn" onClick={this.editEnterprise}>Update</button>}
</div>
</div>
);
}
}
export default AddEnterprise;

How to set default Checked in checkbox 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 :)

Resources