Not able to get values of input type using this.refs... how to get that values from input type
export class BusinessDetailsForm extends Component {
subm
I think the more idiomatic way is to use state
instead of refs
, although it's a little more code in this case since you only have a single input.
export class BusinessDetailsForm extends Component {
constructor(props) {
super(props);
this.state = { googleInput: '' };
this.defaultValue = 'someValue';
this.handleChange = this.handleChange.bind(this);
this.submitForm = this.submitForm.bind(this);
}
handleChange(e) {
const { field, value } = e.target;
this.setState({ [field]: value });
}
submitForm() {
console.log(this.state.googleInput);
}
render() {
return (
<Formsy.Form onSubmit={this.submitForm} id="form_validation">
<Field type="text"
name="googleInput"
onChange={this.handleChange}
component={GoogleAutoComplete}
floatingLabelText="location"
hintText="location"
id="addressSearchBoxField"
defaultValue={this.defaultValue}
onSelectPlace={this.handlePlaceChanged}
validate={[ required ]}
/>
</Formsy.Form>
);
}
}
See https://facebook.github.io/react/docs/forms.html#controlled-components.
In 2018 you should write in constructor this:
In constructor of class you should add something like
this.input = React.createRef()
Examples here: https://reactjs.org/docs/uncontrolled-components.html
Avoid Using Ref
Ref allows you to directly manipulate the DOM, which is against its core concept of Virtual DOM. React discourages us using Refs because of performance issues. But in case of emergency we can use it as below.
class MyComponent extends React.Component{
constructor{
super(props)
this.inputRef = React.createRef()
}
}
and later in our JSX we have to pass is as property named "ref"
<input ref={this.inputRef}/>
refer to official documentation for more detail
You should avoid ref="googleInput"
as it is now considered legacy. You should instead declare
ref={(googleInput) => { this.googleInput = googleInput }}
Inside of your handler, you can use this.googleInput
to reference the element.
Then inside of your submitForm
function, you can obtain the text value with
this.googleInput._getText()
String refs are legacy https://facebook.github.io/react/docs/refs-and-the-dom.html
If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.
Edit
From React 16.3, the format for creating refs are:
class Component extends React.Component
{
constructor()
{
this.googleInput = React.createRef();
}
render()
{
return
(
<div ref={this.googleInput}>
{/* Details */}
</div>
);
}
}
getValue: function() {
return this.refs.googleInput.value;
}