React: State update delay - json

I'm trying to change state by checking radio button. When I check it, it updates the value only after I check the next radio button. If I click first radio button it won't change the state, and if I check the second one it updates state with the previously checked radio button's value. Can anyone help me fixing this?
class App extends React.Component {
state = { checked: false, radioValue: '' }
handleChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
console.log("this.state", this.state); // Gets previous value
this.setState({
[name]: value
});
}
render() {
return (
<div className="wrapper">
<input
name="radioValue"
type="radio"
value="aaa"
checked={this.state.radioValue === 'aaa'}
onChange={this.handleChange} />First Radio Button
<br />
<input
name="radioValue"
type="radio"
value="bbb"
checked={this.state.radioValue === 'bbb'}
onChange={this.handleChange} />Second Radio Button
</div>
);
}
}
export default App;

this.setState({
[name]: value
},()=>console.log(this.state));
you can also check like this by using callback in setstate

Please try this.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: ""
};
}
handleChange = (event) => {
console.log("this.state", this.state); // Gets previous value
this.setState({
checked: event.target.value
});
}
render() {
return (
<div className="wrapper">
<input name="radioValue" type="radio" value="aaa"
checked={this.state.checked === 'aaa'}
onChange={this.handleChange} />
First Radio Button
<br />
<input name="radioValue" type="radio" value="bbb"
checked={this.state.checked === 'bbb'}
onChange={this.handleChange} />
Second Radio Button
</div>
);
}
}
It works well on my machine.

Related

Convert HTML form with action to React form submit with logic

Folks, I think I'm either missing something here or I don't know what I don't know.
What I have is:
<form action="/orders/populate" method="post">
<input type="hidden" name="name" id="name"/>
<input type="hidden" name="rating" id="rating"/>
<input type="submit" name="commit" value="Rate Now" />
</form>
What I want to do is:
Class myComponent extends React.PureComponent {
handleSubmit(e) {
e.preventDefault(); // don't know if this is necessary
sendAnalytics();
// then form submit
}
render () {
return (
<form action="/orders/populate" method="post" onSubmit={this.handleSubmit.bind(this)}>
<input type="hidden" name="name" id="name"/>
<input type="hidden" name="rating" id="rating"/>
<input type="submit" name="commit" value="Rate Now" />
</form>
);
}
}
Don't know what has to be done here. Can someone point out an example similar to this? Or perhaps give me a sample code below?
All help appreciated.
Class myComponent extends React.PureComponent {
this.state = {
name: '' // initial value for name
rating: '' // initial value for rating
}
handleInput = e => {
this.setState({[e.target.name]: e.target.value})
}
handleSubmit = e => {
const { name, rating } = this.state;
e.preventDefault(); // yes, this is necessary otherwise it's refresh your page.
sendAnalytics(name, rating); // api call to store in DB. to call API use axios npm package
}
render () {
const { name, rating } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input type="text" name="name" value={name} id="name" onChange={(e) => this.handleSubmit(e)}/>
<input type="text" name="rating" value={rating} id="rating" onChange={(e) => this.handleSubmit(e)}/>
<input type="submit" name="commit" value="Rate Now" />
</form>
);
}
}
Have you looked at the docs for handling forms in React? This will give you insights in how to use forms with react, since it handles a bit different than regular html forms
This is a common problem I've faced in React. You have one of three ways:
1) Use a third party React-Form library to do the job. There are several.
2) Use React-hooks (a very recent addition to React).
3) Create a generic Form class to handle this state management for you...like so:
export default class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
values: {}
};
}
#boundMethod
handleSubmit(event) {
event.preventDefault();
this.props.submit(this.state.values);
}
#boundMethod
handleChange(event) {
const { name, value } = event.target;
const newValues = Object.assign(
{ ...this.state.values },
{ [name]: value }
);
this.setState({
values: newValues
});
}
public render() {
const { values } = this.state;
return (
<form onSubmit={this.handleSubmit} noValidate={true}>
<div>
{React.Children.map(
this.props.children,
child => (
{React.cloneElement(child, {
value: values[child.props.name],
onChange: this.handleChange
})}
)
)}
<div>
<button type="submit">
Submit
</button>
</div>
</div>
</form>
);
}
}
Then you will be able to use this Form class like so:
<Form
submit={values => {
/* work with values */
}}
>
<input type="hidden" name="name" />
<input type="hidden" name="rating" />
</Form>;
PS:
Keep in mind boundMethod Decorator is something that is not natively available but a module called 'autobind-decorator' I tend to use a lot to deal with this not being bound.

React-Redux is not rendering data correctly inside input/textarea box

I have the example below where (1) and (2) would display the value of "Some Text" instead of Data.preview but (3) would show up Data.preview value just fine. I understand that case (1) - based on this article (ReactJS component not rendering textarea with state variable) wouldn't work for react but why does case (2) return "Some Text" (I also tried value=) instead of Data.preview value like case (3). I do not want it to be a placeholder so it would be editable. Thanks
render(){
const { Data } = this.props
return (
{Data.preview} {*/this would return the value correctly*/}
(1) <textarea className="form-control" maxLength="50" rows="3">{ Data.preview || "Some Text" }</textarea>
(2) <textarea className="form-control" maxLength="50" rows="3" defaultValue={ Data.preview || "Some Text"}></textarea> {*/or use value = {}, either would return "Some Text" */}
(3) <textarea className="form-control" placeholder={Data.preview || "Some Text"} maxLength="50" rows="3"></textarea>{*/ this would return Data.preview value */}
)
}
The textarea can take the value property for showing its current value, and then use the onChange handler to update that value.
In this sample I added both the one with no value yet, and the one which has a default value.
An important note would be that a value cannot be null; it has to be either undefined or empty.
The answer here doesn't really involve redux, but rather a component state for editing the value. I hope this helps enough to use it, applying it to your code.
const { Component } = React;
class DataEntrySample extends Component {
constructor( props ) {
super();
this.state = {
data: props.value
};
this.updateData = this.updateData.bind(this);
}
updateData(e) {
this.setState({ data: e.target.value });
console.log('changed to :' + e.target.value );
}
render() {
return (
<textarea
value={this.state.data}
onChange={this.updateData}
placeholder={this.state.data || 'Enter your data'}>
</textarea>
);
}
}
const target = document.querySelector('#container');
ReactDOM.render( <div><DataEntrySample /><DataEntrySample value="Some text" /></div>, target );
<script id="react" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script id="react-dom" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<div id="container"></div>
If you really want to do it through defaultValue, you have a chance to do that as well (as long as you define an onChange handler that updates the value somewhere).
There is rather a caveat, namely, it will not update any changes from outside of it's view, unless it can define that it has really changed, and with defaultValue. So the following example would work, changing the props from outside would not work.
const { Component } = React;
class DataEntrySample extends Component {
constructor( props ) {
super();
this.state = {
data: props.value
};
this.updateData = this.updateData.bind(this);
}
updateData(e) {
this.setState({ data: e.target.value });
console.log('changed to :' + e.target.value );
}
render() {
return (
<textarea
onChange={this.updateData}
defaultValue={this.state.data || 'Enter your data'}>
</textarea>
);
}
}
class ParentEntry extends Component {
constructor() {
super();
this.updateProps = this.updateProps.bind(this);
this.state = {
value: 'initial text'
};
}
updateProps( value ) {
this.setState({ value });
}
render() {
const { value } = this.state;
console.log( 'render' );
return (
<div>
<h1>With default value</h1>
<DataEntrySample value={value} />
<br />
<button onClick={()=>this.updateProps('empty text')} type="button">
Will set text to empty text
</button>
</div>
);
}
}
const target = document.querySelector('#container');
ReactDOM.render( <ParentEntry />, target );
<script id="react" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.js"></script>
<script id="react-dom" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.js"></script>
<div id="container"></div>
You need to learn a bit more about controller components https://reactjs.org/docs/forms.html
If you then decide that you really need uncontrolled components: https://reactjs.org/docs/uncontrolled-components.html

React Bootstrap CheckBox not toggling 'checked' Prop on Selection

I am fairly new to React Bootstrap and I have been having an annoying issue with checkboxes in a form I am creating.
They won't stay checked when selected after my state updates. They will if I check them again.
I created a toggling function that appends input from selected check boxes in state and sets the checked prop to true. checked={true}
I have written it two ways, both not working.
handleToggle(e) {
e.preventDefault()
const selectedBox = "cb" + e.target.value
this.setState({ goals: this.state.goals + e.target.value, [selectedBox]: e.target.checked })
}
handleToggle(e) {
e.preventDefault()
const selectedBox = "cb" + e.target.value
this.setState({ goals: this.state.goals + e.target.value, [selectedBox]: true })
}
What has been frusturating is that proper values are updating in the state. I threw a debugger in and can see the current state containing a true value for the selected check boxes and the user input appending to whatever is currently under the goals key.
Any direction appreciated. This has been taking a while to debug. Thanks.
Full component -
import React from 'react';
import { connect } from 'react-redux';
import { Button, form, FormGroup, Checkbox, Radio, option, ControlLabel, FormControl, ProgressBar, Pagination, Form } from 'react-bootstrap';
import DatePicker from "react-bootstrap-date-picker";
import { handleChange } from '../helpers';
class Portfolio extends React.Component {
constructor(props) {
super(props)
var value = new Date().toISOString();
this.state = {
date: value,
experience: 1,
progress: 0,
active: false,
goals: "",
cb1: false,
cb2: false,
cb3: false,
cb4: false,
cb5: false
}
this.handleSelect = this.handleSelect.bind(this)
this.handleToggle = this.handleToggle.bind(this)
}
handleSelect(eventKey) {
if (this.state.active === false) {
this.setState({ experience: eventKey, progress: this.state.progress += 20, active: true })
} else {
this.setState({ experience: eventKey })
}
}
handleToggle(e) {
e.preventDefault()
const selectedBox = "cb" + e.target.value
this.setState({ goals: this.state.goals + e.target.value, [selectedBox]: e.target.checked })
}
render() {
const stats = this.props.user.stats
if (!stats || stats.length === 0) {
return(
<div className="portfolio-form-main">
<div className="portfolio-form-container-title-div">
<h1 className="portfolio-title">Profile Information</h1>
</div>
<div className="portfolio-form-container">
<form className="portfolio-form">
<ProgressBar active now={this.state.progress} />
<FormGroup>
<ControlLabel>Choose Your Goals.</ControlLabel>
<Checkbox checked={this.state.cb1} onChange={this.handleToggle} value="1" >
Lose Some Weight
</Checkbox>
{' '}
<Checkbox checked={this.state.cb2} onChange={this.handleToggle} value="2">
Build Strength and Muscle
</Checkbox>
{' '}
<Checkbox checked={this.state.cb3} onChange={this.handleToggle} value="3">
General Health and Wellness
</Checkbox>
{' '}
<Checkbox checked={this.state.cb4} onChange={this.handleToggle} value="4">
Compete in an Event
</Checkbox>
{' '}
<Checkbox checked={this.state.cb5} onChange={this.handleToggle} value="5">
Rehab an Injury
</Checkbox>
</FormGroup>
<FormGroup>
<ControlLabel>Rate Your Exercise Experience Level.</ControlLabel>
<Pagination
bsSize="medium"
items={10}
activePage={this.state.experience}
onSelect={this.handleSelect}
/>
</FormGroup>
<FormGroup>
<ControlLabel>When is Your Birthday?</ControlLabel>
{' '}
<DatePicker value={this.state.value}/>
</FormGroup>
<ControlLabel>How Tall Are You?</ControlLabel>
{' '}
<Form inline>
<FormGroup>
<FormControl type="number"/>
{' '}
<FormControl componentClass="select" placeholder="select">
<option value="select">Unit</option>
<option value="other">in</option>
<option value="other">cm</option>
</FormControl>
</FormGroup>
</Form>
<ControlLabel>How Much Do You Weigh?</ControlLabel>
{' '}
<Form inline>
<FormGroup>
<FormControl type="number"/>
{' '}
<FormControl componentClass="select" placeholder="select">
<option value="select">Unit</option>
<option value="other">Lbs</option>
<option value="other">Kgs</option>
</FormControl>
</FormGroup>
</Form>
<FormGroup >
<ControlLabel>Tell Us About Yourself.</ControlLabel>
{' '}
<FormControl componentClass="textarea" placeholder="textarea" />
</FormGroup>
<Button bsStyle="primary">
Submit
</Button>
</form>
</div>
</div>
)
}
return(
<div>
<ul>
<li>{stats.birthdate}</li>
<li>{stats.weight} {stats.weight_unit}</li>
<li>{stats.height} {stats.height_unit}</li>
<li>{stats.experience}</li>
<li>{stats.about_me}</li>
</ul>
</div>
)
}
}
export default Portfolio
Removing e.preventDefault() from the handleToggle function in your answer should eliminate the need for a forced page refresh.
When a checkbox is clicked React compares the previous value with the next value to decide whether a change has occurred. If it has then a change event is queued.
It seems that React queries the DOM for the checked value before handleToggle is called, so the checkbox value is True. Then preventDefault() executes so the checkbox value in the DOM is now False, but React has set the value as True.
So when using preventDefault() with checkboxes (and possibly radio buttons) you get inconsistencies between the DOM and React.
This works perfectly for selecting and deselecting checkboxes and setting state, adding and removing checked values.
handleToggle(e) {
e.preventDefault()
const selectedBox = "cb" + e.target.value
if (this.state.goals.includes(e.target.value)) {
const goal = this.state.goals.replace(e.target.value, '')
this.setState({ goals: goal, [selectedBox]: e.target.checked })
} else {
this.setState({ goals: this.state.goals + e.target.value, [selectedBox]: e.target.checked })
}
this.props.requestUser(this.props.match.params.userId);
}

How to reset ReactJS file input

I have file upload input:
<input onChange={this.getFile} id="fileUpload" type="file" className="upload"/>
And I handle upload this way:
getFile(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = (theFile) => {
var data = {
blob: theFile.target.result, name: file.name,
visitorId: this.props.socketio.visitorId
};
console.log(this.props.socketio);
this.props.socketio.emit('file-upload', data);
};
reader.readAsDataURL(file);
}
If I upload same file twice, then upload event is not fired. How can I fix that? For simple js code it was enough to do the following: this.value = null; in change handler. How can I do it with ReactJS?
I think you can just clear the input value like this :
e.target.value = null;
File input cannot be controlled, there is no React specific way to do that.
Edit For old browsers (<IE11), you can use one of the following techniques.
See http://jsbin.com/zurudemuma/1/edit?js,output (tested on IE10 & 9)
What worked for me was setting a key attribute to the file input, then when I needed to reset it I update the key attribute value:
functionThatResetsTheFileInput() {
let randomString = Math.random().toString(36);
this.setState({
theInputKey: randomString
});
}
render() {
return(
<div>
<input type="file"
key={this.state.theInputKey || '' } />
<button onClick={this.functionThatResetsTheFileInput()} />
</div>
)
}
That forces React to render the input again from scratch.
This work for me - ref={ref => this.fileInput = ref}
<input id="file_input_file" type="file" onChange={(e) => this._handleFileChange(e)} ref={ref=> this.fileInput = ref} />
then in my case once the file was uploaded to the server , I clear it by using the statement below
this.fileInput.value = "";
I do it by updating key inside my file input.
This will force a re-render and previously selected file will go away.
<input type="file" key={this.state.inputKey} />
Changing the state inputKey will re-render the component.
One way to change the inputKey will be to always set it to Date.now() on click of a button which is supposed to clear the field.
With every click onClick you can reset the input, so that even with the same file onChange will be triggered.
<input onChange={this.onChange} onClick={e => (e.target.value = null)} type="file" />
import React, { useRef } from "react";
export default function App() {
const ref = useRef();
const reset = () => {
ref.current.value = "";
};
return (
<>
<input type="file" ref={ref} />
<button onClick={reset}>reset</button>
</>
);
}
The following worked for me using React Hooks. This is done using what is known as a "controlled input". That means, the inputs are controlled by state, or their source of truth is state.
TL;DR Resetting the file input was a two-step process using both the useState() and useRef() hooks.
NOTE: I also included how I reset a text input in case anyone else was curious.
function CreatePost({ user }) {
const [content, setContent] = React.useState("");
const [image, setImage] = React.useState(null); //See Supporting Documentation #1
const imageInputRef = React.useRef(); //See Supporting Documentation #2
function handleSubmit(event) {
event.preventDefault(); //Stop the pesky default reload function
setContent(""); //Resets the value of the first input - See #1
//////START of File Input Reset
imageInputRef.current.value = "";//Resets the file name of the file input - See #2
setImage(null); //Resets the value of the file input - See #1
//////END of File Input Reset
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add Post Content"
onChange={event => setContent(event.target.value)}
value={content} //Make this input's value, controlled by state
/>
<input
type="file"
onChange={event => setImage(event.target.files[0])} //See Supporting Doc #3
ref={imageInputRef} //Apply the ref to the input, now it's controlled - See #2
/>
<button type="submit">Submit Form</button>
</form>
</div>
)
};
Supporting Documentation:
useState Hook
Returns a stateful value, and a function to update it.
useRef Hook
If you pass a ref object to React, React will set its current property to the corresponding DOM node whenever that node changes.
Using files from web apps
If the user selects just one file, it is then only necessary to consider the first file of the list.
You can also include this in your input element if you know you are not going to be using the built-in file input value at all.
<input value={""} ... />
This way the value is always reset to the empty string on render and you don't have to include it awkwardly in an onChange function.
I know file input is always uncontrolled however the following code still works in my own porject, I can reset the input with no problems at all.
constructor(props) {
super(props);
this.state = {
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.removeImage = this.removeImage.bind(this);
}
handleChange(event) {
if (event.target.files[0]) {
this.setState({
selectedFile: event.target.files[0],
selectedFileName: event.target.files[0].name,
imageSrc: window.URL.createObjectURL(event.target.files[0]),
value: event.target.value,
});
}
}
// Call this function to reset input
removeImage() {
this.setState({
selectedFile: undefined,
selectedFileName: undefined,
imageSrc: undefined,
value: ''
})
}
render() {
return (
<input type="file" value={this.state.value} onChange={this.handleChange} />
);
}
We can reset file input by using key = {this.state.fileInputKey} and initialsing fileInputKey to Date.now() in constructor state.
On file upload success , we need to again assign fileInputKey: Date.now(), so it will have different value than previous and it create new file input component on next render()
We can also do this manually by clicking button to clear/reset file Input
Below is the working code :
import React from "react";
import { Button } from "reactstrap";
class FileUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
fileInputKey: Date.now(),
message: ""
};
this.handleClear = this.handleClear.bind(this);
this.onClickHandler = this.onClickHandler.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
}
onChangeHandler = event => {
this.setState({
selectedFile: event.target.files
});
};
onClickHandler = () => {
if (this.state.selectedFile === null) {
this.setState({
message: "Please select File"
});
return;
}
//axios POST req code to send file to server
{
/**
const data = new FormData()
data = this.state.selectedFile[0]
axios.post("http://localhost:8080/api/uploadFile/", data)
.then(res => {
if (res.status == 200) {
// upload success
}
})
.catch(err => {
//message upload failed
})
*/
}
//after upload to server processed
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: "File Uploaded"
});
};
handleClear() {
this.setState({
selectedFile: null,
fileInputKey: Date.now(),
message: ""
});
}
render() {
return (
<div>
<input
type="file"
key={this.state.fileInputKey}
class="form-control"
onChange={this.onChangeHandler}
/>
<button
type="button"
class="btn btn-success btn-block"
onClick={this.onClickHandler}
>
Upload
</button>
<Button
type="button"
value="Clear"
data-test="clear"
onClick={this.handleClear}
>
{" "}
Clear{" "}
</Button>
<br />
<label>{this.state.message}</label>
</div>
);
}
}
export default FileUpload;
Here is my solution using redux form
class FileInput extends React.Component {
constructor() {
super();
this.deleteImage = this.deleteImage.bind(this);
}
deleteImage() {
// Just setting input ref value to null did not work well with redux form
// At the same time just calling on change with nothing didn't do the trick
// just using onChange does the change in redux form but if you try selecting
// the same image again it doesn't show in the preview cause the onChange of the
// input is not called since for the input the value is not changing
// but for redux form would be.
this.fileInput.value = null;
this.props.input.onChange();
}
render() {
const { input: { onChange, value }, accept, disabled, error } = this.props;
const { edited } = this.state;
return (
<div className="file-input-expanded">
{/* ref and on change are key properties here */}
<input
className="hidden"
type="file"
onChange={e => onChange(e.target.files[0])}
multiple={false}
accept={accept}
capture
ref={(input) => { this.fileInput = input; }}
disabled={disabled}
/>
{!value ?
{/* Add button */}
<Button
className="btn-link action"
type="button"
text="Add Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
:
<div className="file-input-container">
<div className="flex-row">
{/* Image preview */}
<img src={window.URL.createObjectURL(value)} alt="outbound MMS" />
<div className="flex-col mg-l-20">
{/* This button does de replacing */}
<Button
type="button"
className="btn-link mg-b-10"
text="Change Image"
onPress={() => this.fileInput.click()}
disabled={disabled}
/>
{/* This button is the one that does de deleting */}
<Button
type="button"
className="btn-link delete"
text="Delete Image"
onPress={this.deleteImage}
disabled={disabled}
/>
</div>
</div>
{error &&
<div className="error-message"> {error}</div>
}
</div>
}
</div>
);
}
}
FileInput.propTypes = {
input: object.isRequired,
accept: string,
disabled: bool,
error: string
};
FileInput.defaultProps = {
accept: '*',
};
export default FileInput;
In my case I had a functional component and after selecting a file it suppose to set the file name in the state so using any solution above was failing except the ref one which i fixed like this.
const fileUpload = props => {
const inputEl = useRef(null)
const onUpload = useCallback(e => {
uploadFile(fileDetails)
.then(res => {
inputEl.current.value = ''
})
.catch(err => {
inputEl.current.value = ''
})
})
return (
<input type='file' ref={inputEl} onChange={handleChange} />
<Button onClick={onUpload}>Upload</Button>
)
}
I recently got stumbled into this issue to reset the File type input field. I think it is still a milestone for most developers. So I thought I should share my solution.
Since we are listening to the onChange event to update the image file into some of our states, we will have our component rerendered once we set the state. In such case, we can specify the value of the input file as empty like value='' which will cause the input field to reset its value after each change of its value.
<input
type="file"
value=''
onChange={onChangeFnc}
/>

How to use radio buttons in ReactJS?

I am new to ReactJS, sorry if this sounds off. I have a component that creates several table rows according to the received data.
Each cell within the column has a radio checkbox. Hence the user can select one site_name and one address from the existing rows. The selection shall be shown in the footer. And thats where I am stuck.
var SearchResult = React.createClass({
render: function () {
var resultRows = this.props.data.map(function (result) {
return (
<tbody>
<tr>
<td>
<input type="radio" name="site_name" value={result.SITE_NAME}>
{result.SITE_NAME}
</input>
</td>
<td>
<input type="radio" name="address" value={result.ADDRESS}>
{result.ADDRESS}
</input>
</td>
</tr>
</tbody>
);
});
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name ???? </td>
<td>chosen address ????? </td>
</tr>
</tfoot>
</table>
);
},
});
In jQuery I could do something like $("input[name=site_name]:checked").val() to get the selection of one radio checkbox type and insert it into the first footer cell.
But surely there must be a Reactjs way, which I am totally missing? Many Thanks
Any changes to the rendering should be change via the state or props (react doc).
So here I register the event of the input, and then change the state, which will then trigger the render to show on the footer.
var SearchResult = React.createClass({
getInitialState: function () {
return {
site: '',
address: '',
};
},
onSiteChanged: function (e) {
this.setState({
site: e.currentTarget.value,
});
},
onAddressChanged: function (e) {
this.setState({
address: e.currentTarget.value,
});
},
render: function () {
var resultRows = this.props.data.map(function (result) {
return (
<tbody>
<tr>
<td>
<input
type="radio"
name="site_name"
value={result.SITE_NAME}
checked={this.state.site === result.SITE_NAME}
onChange={this.onSiteChanged}
/>
{result.SITE_NAME}
</td>
<td>
<input
type="radio"
name="address"
value={result.ADDRESS}
checked={this.state.address === result.ADDRESS}
onChange={this.onAddressChanged}
/>
{result.ADDRESS}
</td>
</tr>
</tbody>
);
}, this);
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name {this.state.site} </td>
<td>chosen address {this.state.address} </td>
</tr>
</tfoot>
</table>
);
},
});
jsbin
Here is the simplest way of implementing radio buttons in react js.
class App extends React.Component {
setGender(event) {
console.log(event.target.value);
}
render() {
return (
<div onChange={this.setGender.bind(this)}>
<input type="radio" value="MALE" name="gender"/> Male
<input type="radio" value="FEMALE" name="gender"/> Female
</div>
)
}
}
ReactDOM.render(<App/>, 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>
Edited
You can use arrow function instead of binding. Replace the above code as
<div onChange={event => this.setGender(event)}>
For a default value use defaultChecked, like this
<input type="radio" value="MALE" defaultChecked name="gender"/> Male
Based on what React Docs say:
Handling Multiple Inputs.
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value
});
};
render() {
return (
<div className="radio-buttons">
Windows
<input
id="windows"
value="windows"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Mac
<input
id="mac"
value="mac"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Linux
<input
id="linux"
value="linux"
name="platform"
type="radio"
onChange={this.handleChange}
/>
</div>
);
}
}
Link to example: https://codesandbox.io/s/6l6v9p0qkr
At first, none of the radio buttons is selected so this.state is an empty object, but whenever the radio button is selected this.state gets a new property with the name of the input and its value. It eases then to check whether user selected any radio-button like:
const isSelected = this.state.platform ? true : false;
EDIT:
With version 16.7-alpha of React there is a proposal for something called hooks which will let you do this kind of stuff easier:
In the example below there are two groups of radio-buttons in a functional component. Still, they have controlled inputs:
function App() {
const [platformValue, plaftormInputProps] = useRadioButtons("platform");
const [genderValue, genderInputProps] = useRadioButtons("gender");
return (
<div>
<form>
<fieldset>
Windows
<input
value="windows"
checked={platformValue === "windows"}
{...plaftormInputProps}
/>
Mac
<input
value="mac"
checked={platformValue === "mac"}
{...plaftormInputProps}
/>
Linux
<input
value="linux"
checked={platformValue === "linux"}
{...plaftormInputProps}
/>
</fieldset>
<fieldset>
Male
<input
value="male"
checked={genderValue === "male"}
{...genderInputProps}
/>
Female
<input
value="female"
checked={genderValue === "female"}
{...genderInputProps}
/>
</fieldset>
</form>
</div>
);
}
function useRadioButtons(name) {
const [value, setState] = useState(null);
const handleChange = e => {
setState(e.target.value);
};
const inputProps = {
name,
type: "radio",
onChange: handleChange
};
return [value, inputProps];
}
Working example: https://codesandbox.io/s/6l6v9p0qkr
Make the radio component as dumb component and pass props to from parent.
import React from "react";
const Radiocomponent = ({ value, setGender }) => (
<div onChange={setGender.bind(this)}>
<input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
<input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
</div>
);
export default Radiocomponent;
It's easy to test as it is a dumb component (a pure function).
Just an idea here: when it comes to radio inputs in React, I usually render all of them in a different way that was mentionned in the previous answers.
If this could help anyone who needs to render plenty of radio buttons:
import React from "react"
import ReactDOM from "react-dom"
// This Component should obviously be a class if you want it to work ;)
const RadioInputs = (props) => {
/*
[[Label, associated value], ...]
*/
const inputs = [["Male", "M"], ["Female", "F"], ["Other", "O"]]
return (
<div>
{
inputs.map(([text, value], i) => (
<div key={ i }>
<input type="radio"
checked={ this.state.gender === value }
onChange={ /* You'll need an event function here */ }
value={ value } />
{ text }
</div>
))
}
</div>
)
}
ReactDOM.render(
<RadioInputs />,
document.getElementById("root")
)
<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="root"></div>
import React, { Component } from "react";
class RadionButtons extends Component {
constructor(props) {
super(props);
this.state = {
// gender : "" , // use this one if you don't wanna any default value for gender
gender: "male" // we are using this state to store the value of the radio button and also use to display the active radio button
};
this.handleRadioChange = this.handleRadioChange.bind(this); // we require access to the state of component so we have to bind our function
}
// this function is called whenever you change the radion button
handleRadioChange(event) {
// set the new value of checked radion button to state using setState function which is async funtion
this.setState({
gender: event.target.value
});
}
render() {
return (
<div>
<div check>
<input
type="radio"
value="male" // this is te value which will be picked up after radio button change
checked={this.state.gender === "male"} // when this is true it show the male radio button in checked
onChange={this.handleRadioChange} // whenever it changes from checked to uncheck or via-versa it goes to the handleRadioChange function
/>
<span
style={{ marginLeft: "5px" }} // inline style in reactjs
>Male</span>
</div>
<div check>
<input
type="radio"
value="female"
checked={this.state.gender === "female"}
onChange={this.handleRadioChange}
/>
<span style={{ marginLeft: "5px" }}>Female</span>
</div>
</div>
);
}
}
export default RadionButtons;
Here's what I have used. Hope this helps.
Defining variable first.
const [variableName, setVariableName] = useState("");
Then, we will need the actual radio buttons.
<input
type="radio"
name="variableName"
value="variableToCheck"
onChange={(e) =>
setVariableName("variableToCheck")
}
checked={variableName === "variableToCheck"}
/>
#Tomasz Mularczyk mentions react hooks in his answer, but I thought I'd put in a solution I recently used that uses just the useState hook.
function Radio() {
const [currentRadioValue, setCurrentRadioValue] = useState()
const handleRadioChange = (e) => {
setCurrentValue(e.target.value);
};
return (
<>
<div>
<input
id="radio-item-1"
name="radio-item-1"
type="radio"
value="radio-1"
onChange={handleRadioChange}
checked={currentRadioValue === 'radio-1'}
/>
<label htmlFor="radio-item-1">Radio Item 1</label>
</div>
<div>
<input
id="radio-item-2"
name="radio-item-2"
type="radio"
value="radio-2"
onChange={handleRadioChange}
checked={currentRadioValue === 'radio-2'}
/>
<label htmlFor="radio-item-2">
Radio Item 1
</label>
</div>
</>
);
}
Clicking a radio button should trigger an event that either:
calls setState, if you only want the selection knowledge to be local, or
calls a callback that has been passed in from above self.props.selectionChanged(...)
In the first case, the change is state will trigger a re-render and you can do
<td>chosen site name {this.state.chosenSiteName} </td>
in the second case, the source of the callback will update things to ensure that down the line, your SearchResult instance will have chosenSiteName and chosenAddress set in it's props.
I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.
/*
* A simple React component
*/
class App extends React.Component {
constructor(params) {
super(params)
// initial gender state set from props
this.state = {
gender: this.props.gender
}
this.setGender = this.setGender.bind(this)
}
setGender(e) {
this.setState({
gender: e.target.value
})
}
render() {
const {gender} = this.state
return <div>
Gender:
<div>
<input type="radio" checked={gender == "male"}
onClick={this.setGender} value="male" /> Male
<input type="radio" checked={gender == "female"}
onClick={this.setGender} value="female" /> Female
</div>
{ "Select Gender: " } {gender}
</div>;
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(<App gender="male" />, 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>
To build upon ChinKang said for his answer, I have a more dry'er approach and in es6 for those interested:
class RadioExample extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedRadio: 'public'
};
}
handleRadioChange = (event) => {
this.setState({
selectedRadio: event.currentTarget.value
})
};
render() {
return (
<div className="radio-row">
<div className="input-row">
<input
type="radio"
name="public"
value="public"
checked={this.state.selectedRadio === 'public'}
onChange={this.handleRadioChange}
/>
<label htmlFor="public">Public</label>
</div>
<div className="input-row">
<input
type="radio"
name="private"
value="private"
checked={this.state.selectedRadio === 'private'}
onChange={this.handleRadioChange}
/>
<label htmlFor="private">Private</label>
</div>
</div>
)
}
}
except this one would have a default checked value.
Bootstrap guys, we do it like this:
export default function RadioButton({ onChange, option }) {
const handleChange = event => {
onChange(event.target.value)
}
return (
<>
<div className="custom-control custom-radio">
<input
type="radio"
id={ option.option }
name="customRadio"
className="custom-control-input"
onChange={ handleChange }
value = { option.id }
/>
<label
className="custom-control-label"
htmlFor={ option.option }
>
{ option.option }
</label>
</div>
</>
)
}
import React from 'react';
import './style.css';
export default function App() {
const [currentRadioValue, setCurrentValue] = React.useState('on');
const handleRadioChange = value => {
setCurrentValue(value);
};
return (
<div>
<>
<div>
<input
name="radio-item-1"
value="on"
type="radio"
onChange={e => setCurrentValue(e.target.value)}
defaultChecked={currentRadioValue === 'on'}
/>
<label htmlFor="radio-item-1">Radio Item 1</label>
{currentRadioValue === 'on' && <div>one</div>}
</div>
<div>
<input
name="radio-item-1"
value="off"
type="radio"
onChange={e => setCurrentValue(e.target.value)}
defaultChecked={currentRadioValue === 'off'}
/>
<label htmlFor="radio-item-2">Radio Item 2</label>
{currentRadioValue === 'off' && <div>two</div>}
</div>
</>
</div>
);
}
working example: https://stackblitz.com/edit/react-ovnv2b