How to change the state of the checkbox using a method? - javascript

I need to create a method and change the state of the checkbox from checked to unchecked and vice versa by calling a method.
onEventListener: (event,props) => {
if (event.key === " ") {
console.log ("Check box is "+ !event.target.checked );
props.onEventListener({onChecked: !event.target.checked});
}
onChecked will be used to change the state , It is a boolean .
render (
<div>
<input
type="checkBox"
onKeyDown={props.onEventListener}
defaultChecked = {props.onChecked}
/>
</div>
)

From the official documentation of React.
class Reservation extends React.Component {
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
});
}
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
This handles state changes both for checkboxes and text inputs.

Related

What is the proper way to clear a React Form?

I have a form that has a few different type of elements (textbox, checkbox, etc.) that was created using Reactjs. I have been having a hard time trying to figure out how to clear a form. I've googled and not really sure of those solutions. I tried something like the following but found it was of no use.
What I want to happen is if the user fills out the form and decides to clear the form, once they click 'Clear Form', the form should reset. All the fields need to be blank again.
handleClearForm(){
this.setState({
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
})
}
How can I clear a form in react? Any help would be much appreciated.
Code
Check this improved code
class App extends React.Component{
constructor(){
super()
this.state = {
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
}
}
setdecisionDateValue (value) {
this.setState({
decisionDate: value
})
}
componentDidMount(){
$( "#decisionDate" ).datepicker({
onSelect: this.setdecisionDateValue
});
}
handleClearForm = () => {
this.setState({
decisionDate: '',
Veggies:'',
fullName:'',
comment:''
})
}
handleChange = (e) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({[name]: value})
}
render(){
const { decisionDate,Veggies,fullName,comment} = this.state;
return(
<div>
<input type="text" name="fullName"
placeholder="Full Name"
onChange={this.handleChange}
value={fullName}/><br /><br />
<input type="text"
name="decisionDate"
id="decisionDate"
onChange={this.handleChange}
placeholder="MM/DD/YYYY"
value={this.state.decisionDate} /><br /><br />
<textarea name="comment"
value={comment}
onChange={this.handleChange}/><br /><br />
<input
type="checkbox"
name="Veggies"
onChange={this.handleChange}
checked={Veggies}
/>Veggies<br /><br />
<button onClick={this.handleClearForm}>
Clear Form
</button>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById("root")
)

What is the proper way to use radio in React? The button gets frozen once checked

I'm using state to control my component, and I'm not sure what part of the following code is causing the code to button to freeze once checked.
This is the constructor:
constructor(props) {
super(props);
this.state = {
firstName: '',
inPerson: false,
onlineMedium: true,
};
}
This function should handle change:
handleFormChange = (event) => {
const target = event.target;
if (target.name === "inPerson" || target.name === "onlineMedium") {
const value = !this.state[target.name]
const name = target.name;
this.setState({
[name]: value
});
}
else {
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
}
This renders the component:
render() {
return (
<>
<label className="tutor-add-label">
First name
<input
className="tutor-add-input"
type="text"
name="firstName"
value={this.state.firstName}
onChange={this.handleFormChange}
/>
</label>
<div className="medium">
<input
type="radio"
id="online"
name="onlineMedium"
checked={this.state.onlineMedium}
onChange={this.handleFormChange}
/>
<label htmlFor="online">online</label>
<input
type="radio"
id="person"
name="inPerson"
checked={this.state.inPerson}
onChange={this.handleFormChange}
/>
<label htmlFor="person">In person</label>
</div>
</>
)
}
Edit: As per the comment below, please let me know if there is another way to select/unselect radio that works better. I was following this http://react.tips/radio-buttons-in-react-16/
Update: It seems that the click doesn't happen (after the first click)for some reason. Does that seem to point in any direction?
This is what worked for me:
Changing the event handler from onChange to onClick and using the following to control state:
if (target.name === "onlineMedium" || target.name === "inPerson") {
if (event.target.checked && !this.state[target.name]) {
this.setState({
[target.name]: true,
})
}
else if (event.target.checked && this.state[target.name]) {
this.setState({
[target.name]: false,
})
}
}
Credit: it was inspired by this answer: https://stackoverflow.com/a/57147343/10813256

Checkbox don't show checked

I'm working with checkbox input. When I click on checbox, checkbox don't show checked but checkbox's value I still get. I use React JS
Simple checkbox
import React from 'react';
import callApi from './../../utils/apiCaller'
import { Link } from 'react-router-dom'
class ProductActionPage extends React.Component {
constructor(props) {
super(props);
this.state = {
id: '',
productStatus: ''
}
}
onChange = (e) => {
var target = e.target;
var name = target.name;
var value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
[name]: value
});
}
render() {
var statusCheckbox = this.state.productStatus === 'true' ? true : false;
return (
<div className="row">
<div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<div className="form-group">
<label>Trang thai: </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" checked={statusCheckbox} name="productStatus" onChange={this.onChange} />
Con hang
</label>
</div>
<button type="submit" className="btn btn-primary">Luu lai</button>
<Link to="/product/list" className="btn btn-danger ml-5">Huy bo</Link>
</div>
</div>
);
}
}
How can I show checked checkbox?
this.state.productStatus is a boolean value, so your condition will always give you the false, because you are comparing Boolean === String.
Just change
var statusCheckbox = this.state.productStatus === 'true' ? true : false;
to
var statusCheckbox = this.state.productStatus ? true : false; //It doesn't make any sense
Or simply
var statusCheckbox = this.state.productStatus;
Or you can directly use this.state.productStatus,
<input
type="checkbox"
checked={this.state.productStatus}
name="productStatus"
onChange={this.onChange}
/>

Retrieving value of checkbox in React.js

I want to retrieve the value of my checkbox when it is checked.
I am using this "http://react-component.github.io/checkbox/".
My code looks like this.
<div className="user_box">
{ check.map((values , i)=> {
return <Checkbox
name = "checkbox"
onChange={this.checkvalue.bind(this)}
value={values.username}
/>
})}
</div>
My function:
checkvalue(e){
// var all_users = [];
// var value = this.checkbox.value;
// all_users.push(value);
// console.log(all_users);
console.log('checkbox checked:', (e.target.checked));
}
I'm not understanding how to retrieve the value of the checkbox.
you need to pass the "e, Synthetic event parameter to your handler" :
handleChange(e) {
let isChecked = e.target.checked;
// do whatever you want with isChecked value
}
render() {
// ... your code here
return (
{/* your other jsx here */}
<Checkbox otherProps onChange={e => this.handleChange(e)} />
{/* your other jsx here */}
);
}
Use the Synthetic event parameter, here is an example:
const element1 = "boy";
const element2 = "girl";
<input
type="checkbox"
name={element1}
value={element1}
onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
</label>
<input
type="checkbox"
name={element2}
value={element2}
onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
</label>
handleChange = (e) => {
// to find out if it's checked or not; returns true or false
const checked = e.target.checked;
// to get the checked value
const checkedValue = e.target.value;
// to get the checked name
const checkedName = e.target.name;
//then you can do with the value all you want to do with it.
};
Try this :
getChckeboxValue(event) {
const value = event.target.value;
}
In render:
<input onClick={this.getChckeboxValue.bind(this)} type="checkbox" value="Text" />
We can get check box value by declaring onChange={this.likeClicked} defaultChecked={false} on input element properties
constructor(props){
super(props)
this.likeClicked = this.likeClicked.bind(this)
}
likeClicked(){
console.log(event.target.checked, event.target.id);
}
render(){
return (
<div className='px-3'>
<div className='item-header item-wrapper cirle'>
<input
type="checkbox"
onChange={this.likeClicked}
defaultChecked={false}
className="checkbox"
id={`checkbox_${this.props.product.sku}`}
/>
<label htmlFor={`checkbox_${this.props.product.sku}`}>
<HeartIcon className="heart-svg"></HeartIcon>
</label>
</div>
</div>
);
}
One liner:
onChange={e => doSomethingWithValue( e.currentTarget.checked )}

Working with Radio Buttons on Flux

Just started my first app in React and I want to know if there is a React way to work with Radio Buttons, I have a form with 4 radio buttons, I need to take 2 of the options selected and send that info to a backend.
class RadioBtns extends Component {
constructor (props) {
super(props);
this.state = {
greet : '',
hello : '',
};
}
render () {
return (
<div>
<div>
<form>
<input type="radio" value="first" name="greet" onChange={this._onChangeGreet}/> Option 1
<input type="radio" value="second" name="greet" onChange={this._onChangeGreet}/> Option 2
<input type="radio" value="three" name="hello" onChange={this._onChangeHello}/> Option 3
<input type="radio" value="four" name="hello" onChange={this._onChangeHello}/> Option 4
</form>
<hr />
<button type="submit" onClick={this._submitSettings}>YES!</button>
</div>
</div>
);
}
_onChangeGreet = ({ target }) => {
this.setState({
greet : target.value,
});
}
_onChangeHello = ({ target }) => {
this.setState({
hello : target.value,
});
}
_submitSettings = () => {
console.log('submit');
}
}
export default RadioBtns;
how do I send this states with the values to the stores ?
and here I have the action
#createActions(flux)
class RadioBtnsActions {
constructor () {
this.generateActions('optionSelected');
}
}
export default RadioBtnsActions;
and in the Store
import flux from 'flux';
import RadioBtnsActions from 'actions/RadioBtnsActions';
#createStore(flux)
class RadioBtnsStore {
constructor () {
this.state = {
radioSelected : false,
};
}
#bind(RadioBtnsActions.optionSelected)
optionSelected (option) {
this.setState({
radioSelected : option,
});
}
}
export default RadioBtnsStore;
Here's what we did in our project (simplified, use your imagination):
First you create a RadioButton component that renders the actual input:
render(){
<div>
<input id={this.props.id} type="radio"
name={this.props.name} value={this.props.value}
checked={this.props.checked} onChange={this.onChange}/>
<label htmlFor={this.props.id}>{this.props.label}</label>
</div>
},
onChange: function(ev){
this.props.onChange(ev.target.checked, this.props.value);
}
Then you use that to implement a RadioButtonGroup component:
render: function(){
var name = this.name, value = this.props.value, onChange = this.onSingleRadioChange;
var options = _.map(this.props.options, function(option){
var id = name + '-' + option.value;
return <RadioButton key={option.value} id={id} name={name} value={option.value} label={option.label} checked={option.value == value} onChange={onChange} />
});
return <div>{options}</div>
},
onSingleRadioChange: function(checked, value){
if(checked)
this.props.onChange(value);
}
You can use it like this:
<RadioButtonGroup name='greet' options={[{value: 'first', label: 'First'}, {value: 'second', label: 'Second'}]} onChange={val => { Actions.radioGroupChanged('greet', val);}} />
Where Actions.radioGroupChanged is the action that your store is listening on.
Don't forget to use labels for better UX.
Edit: here's a rough draft of the store, although we use Reflux, so it's a different API that what you have:
var store = Reflux.createStore({
radioGroups: {greet: 'first', hello: 'three'}, //state of the radio button groups lives here
init(){
this.listenTo(Actions.radioGroupChanged, this.onRadioGroupChanged);
},
onRadioGroupChanged(group, value){
this.radioGroups[group] = value;
this.trigger(); //this notifies the component that the store changed;
}
});
The component then listens to the store and updates its own state:
componentDidMount(){
this.listenTo(store, () => { this.setState({radios: store.groups}) });
}
render(){
return <RadioButtonGroup name='greet' value={this.state.radios.greet} .../>
}

Categories

Resources