Reactjs : Read value of a Radio Button - javascript

I have the following code for radio selection control:
<Radio
inline
id={item}
enter code herename="stackedRadios"
value={item}
label={item}
checked={this.state.checked == item}
onChange={this.handleChange.bind(this, item, quesId)}
/>
The handle change function is :
handleChange (value, quesId) {
this.setState({checked: value})
}
In the handle change function what I am trying to print the value on console but nothing is printed on console.
Now what I want is to get the selected value from the radio but failing to get so. Please help with the same.

Since you've used bind with 2 args, event which is normally the first arg, will be the third.
handleChange (value, quesId, event) {
this.setState({ checked: event.target.checked })
}
If you don't need the first two values then don't bind. Also you shouldn't use bind inside of render as this causes the Radio component to have new props every render even if nothing changed, since a new function is created every render.

Related

Get selected value from react bootstrap AsyncTypeHead

I am using react bootstrap AsyncTypeHead. I type keywords and it suggests values from the backend, then I click one of the suggestions and try to get the value selected, but it seems event does not exist. It throws all kind of errors. What could be the issue? I am trying to do it through onChange attribute with event.target.value:
<AsyncTypeahead
filterBy={filterBy}
id="async-example"
isLoading={isLoading}
labelKey="login"
minLength={3}
onSearch={handleSearch}
onChange={ (event) => setCitiesSend([...citiesSend, event.target.value])}
If instead event.target.value I put alert('test') it throws alert multiple times. It seems to be changing on each typed letter.
Full example: React Bootstrap Typeahead - Asynchronous Searching
The onChange function returns a value.
So, your code will be.
<AsyncTypeahead
filterBy={filterBy}
id="async-example"
isLoading={isLoading}
labelKey="login"
minLength={3}
onSearch={handleSearch}
onChange={ (value) => setCitiesSend((previous) =>[...previous, ...value])}
/>

Check for a value onClick react

In my render method i render some cards that all have button and when i click on the button i want to disabled them.
Those buttons are checking if the value of the array is true and if it is it's disabling the button but this is only working when i refresh the page and i want the button to be disabled directly on click
Here is my try
//this is checking from my database if it include the id of the pokemon that i want to get
const check = pokemon.id
const newPoke = getPokemon.includes(check);
// Here is the button that is getting disabled only if newPoke return true
<Button isDisabled={newPoke}/>
Everything work correctly when i refresh the page the buttons that i clicked previously get disabled but not onClick directly.
I think after i click i have to re-check for newPoke but i'm not sure how to include it in the button
You are using props to pass variable from parent to children(Button).
reactjs documentation states react props are read-only
If you are planing to change the values of newPoke then you should rethink your structure and maybe its best to use states in your example
For example here
<Button isDisabled="newPoke"></Button will only be checked at initialization stage since its a react prop. but if you used state which gets updated with every new action you can have a true one-way binding and your ui would reflect data changes quickly
store the newPoke in state and change it's value when the button is clicked. and use that value in button isDisabled prop. try something like this
state={
isDisabled: false;
}
handleClick=(isDisabled)=>{
this.setState({isDisabled});
}
//this is checking from my database if it include the id of the pokemon that i want to get
const check = pokemon.id
const newPoke = getPokemon.includes(check);
// Here is the button that is getting disabled only if newPoke return true
return(
<Button isDisabled={this.state.isDisabled} onClick={()=>this.handleClick(newPoke )}/>
);
i think if you want get value from database you can use componentDidMount().
and your value you can save while in state. and then in function handleClick you can change this state
for example :
handleClick = () => {
const value = this.state.valueFromDataBase
this setState({valueFromDataBase: false})
}
and in render you declare this value state
render(){
return(
<Button defaultValue={this.state.valueFromDataBase} onCLick={this.handleClick} />
)
}
please correct my answer if I am wrong in responding to your question

react-md SelectField onChange not updating properly

I'm using the 'react-md' library and I am trying to use the SelectField component, but when I send a function for onChange the select field no longer updates as it's supposed to.
handleSelection = (value, index, event, details) => {
// "details.id" is the id of the field which I am using to keep track of state
this.setState({[details.id]: value});
}
render() {
const STRING_SELECTORS = ['At most', 'At least'];
return(
<div>
<SelectField
id="calories-selector"
className="md-cell selector md-cell--5"
menuItems={STRING_SELECTORS}
defaultValue="At most"
onChange={this.handleSelection)
/>
)
}
When I don't call this.setState() in the handleSelection function, the menu changes as expected when clicking an item, however when I do call setState, it updates the selection on a delay. If the menu says "At most" and I click "At least" it will stay at "At most" then if I click "At most" it will then change the "At least".
I've had a similar issue with input fields, and to solve this I used onBlur instead of onChange, but the react-md library's onBlur doesn't get triggered in the way that I need.
You can use the value prop of SelectField component. Create a state and bind it to the SelectField value prop and update the state at onChange event to the selected value.

Input form - change the running order of onChange and isDisabled

I have implemented in React a webpage with 3 input fields, each one with the properties of
onChange={this.handleChange} and disabled={this.isDisabled()}
The desired behavior is that when an input field contains 2 digits, the focus will be moved to the next input field.
As long as the field doesn't contain 2 digits, the fields next to must be disabled.
What actually happens, when I type the second digit in the first field, it runs the handleChange function, that function checks whether the field contains 2 digits, find out that yes, and moves the focus to the next input field.
But the next field is disabled! (because the isDisabled function didn't run yet!)
So the cursor doesn't move..
I want to change the order of the happenings, or any other way to solve it.
Do you have any suggestions?
The problem is that this.isDisabled() runs immediately in render but this.handleChange runs on click and most possibly doesn't change the state thus no rerender.
You sholdn't run function on next input, you should pass true or false to its disabled prop. Just make handleChange update the state which defines which fields are disabled. And pass that state to your inputs accordingly.
I had faced the same issue a few days back. My approach was however using react states and focusing the input by its id, that was fetched from state;
So first we make a input - id map for our convenience. And use document.getElementById(this.state.active).focus() function. We change our state via our change handler.
render() {
this.setInputFocus();
return (
<div className="App">
<input id="1" onChange={this.onChange} />
<input id="2" onChange={this.onChange} />
<input id="3" onChange={this.onChange} />
</div>
);
}
setInputFocus = () => {
if (document.getElementById(this.state.active)) {
document.getElementById(this.state.active).focus();
}
};
onChange = e => {
if (e.target.value.length === 2) {
this.setState({ active: this.state.active + 1 });
}
};
Here is a full code that somewhat solves the issue

React-Bootstrap onClick triggers accumulate(?) and execute many times on checkbox

What I'm experiencing is what seems like onClick listeners accumulating across renders and firing more and more times as I toggle a checkbox.
I'm mapping over an array to generate the checkboxes, like this:
const list = permissions[cat].map((p) => {
// map the role's permissions to the checked state of the "all" permission checkboxes
const checked = _.findWhere(role.permissions, {id: p.id}) ? true : false;
return <CheckBox key={p.id}
checked={checked}
label={p.operation}
onChange={e => this.togglePermission(p.id)} />;
});
the checkbox looks like this:
const CheckBox = ({ checked, label, onChange }) => (
<Input
checked={checked}
type="checkbox"
label={prettyPrint(label)}
onChange={onChange} />
);
and this.togglePermssion looks like this:
togglePermission(id) {
this.props.togglePermissionOnRole(id);
}
What's happening is that when I toggle a checkbox, the redux action is dispatched and the component is re-rendered. When I toggle a checkbox again (the same or another), this.togglePermission is called again multiple times. As I toggle more checkboxes, the amount of times it's executed seems to grow exponentially.
Any ideas as to why this behaviour happens?
I actually figured this out - turns out it was Rollbar's JS snippet the whole time.

Categories