Possible to Interact with Custom Javascript Object Handler - reactjs

I am trying to migrate the handling of my bootstrap date range picker from jQuery to ReactJS and while I am able to handle most interactions, I am struggling to figure out how I can migrate the following method to my reactjs setup>
This interaction takes the values selected from the calendar component on "Apply" and then sets two hidden input fields that I have that are sent to my server on form submission.
jQuery:
//Set annotationDateRange value on picker selection
$('input[name="annotationDateRange"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
$("input[name='annotationStartDate']").val(picker.startDate.format('MM/DD/YYYY'));
$("input[name='annotationEndDate']").val(picker.endDate.format('MM/DD/YYYY'));
});
ReactJS (I thought add the handleChange() to the field would pick up on the calendar selection changes, but it appears they populate the text field in a way that the virtual DOM does not pick up on it):
import React from 'react';
import isEqual from 'lodash/isEqual';
export default class DateFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
startDateValue: this.props.startDateQuery ? this.props.startDateQuery: '',
endDateValue:this.props.endDateQuery ? this.props.endDateQuery: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log("New Handle Change")
/*console.log(input + " " + value)
this.setState({
[input]: value
})*/
}
componentDidMount() {
this.setState({
startDateValue: this.props.startDateQuery,
endDateValue: this.props.endDateQuery
});
}
componentWillReceiveProps(nextProps) {
if (this.props.startDateQuery != nextProps.startDateQuery && this.props.endDateQuery != nextProps.endDateQuery){
this.setState({ startDateValue: nextProps.startDateQuery, endDateValue: nextProps.endDateQuery });
}
}
render() {
return (
<div className="col-md-3">
<div className="input-group annotation-filter-date-range-picker">
<p>Annotation Date Range:</p>
</div>
<div className="input-group annotationFilterDatePicker">
<span className="input-group-addon"><i className="glyphicon glyphicon-calendar"></i></span>
<input type="text" name="annotationDateRange" className="form-control annotationFilterDatePicker" onChange={this.handleChange} autoComplete="off" />
</div>
<input type="hidden" name="annotationStartDate" className="form-control" value={this.state.startDateValue ? this.state.startDateValue : ""} onChange={this.handleChange} />
<input type="hidden" name="annotationEndDate" className="form-control" value={this.state.endDateValue ? this.state.endDateValue : ""} onChange={this.handleChange} />
</div>
);
}
}

Use arrow functions to not lose the Component scope.
handleChange = (event) => {
this.setState({
[input]: value
})
}
Or you can just call it as an arrow function
<input type="text" name="annotationDateRange" className="form-control annotationFilterDatePicker" onChange={(event) => this.handleChange(event)} autoComplete="off" />
In a NON ES6 way you can just bind 'this' to the function.
<input type="text" name="annotationDateRange" className="form-control annotationFilterDatePicker" onChange={this.handleChange.bind(this)} autoComplete="off" />

Related

How do I fix a component is changing from controlled input of the type text to be uncontrolled. Reactjs Error [duplicate]

This question already has answers here:
A component is changing an uncontrolled input of type text to be controlled error in ReactJS
(27 answers)
Closed 3 years ago.
I have set the initial state to blanks than why am I encountering this error ? What should I change next ?
I am fetching users from the database using ID and then trying to update their value. I get this error for the first attempt only. subsequent attempts works perfectly.
could there be problem with the backend ?
import React, { Component } from 'react';
import axios from 'axios';
export default class EditUsers extends Component {
constructor(props)
{
super(props);
this.onchangeUsername = this.onchangeUsername.bind(this);
this.onchangeAddress = this.onchangeAddress.bind(this);
this.onchangePhoneno = this.onchangePhoneno.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username:'',
address:'',
phoneno:''
}
}
componentDidMount() {
axios.get('http://localhost:5000/users/'+this.props.match.params.id)
.then(response=>{
this.setState({
username:response.data.username,
address:response.data.address,
phoneno:response.data.phoneno,
})
})
.catch(function (error) {
console.log(error);
})
}
onchangeUsername(e)
{
this.setState({
username:e.target.value
});
}
onchangeAddress(e)
{
this.setState({
address:e.target.value
});
}
onchangePhoneno(e)
{
this.setState({
phoneno:e.target.value
});
}
onSubmit(e){
e.preventDefault();
const user =
{
username:this.state.username,
address:this.state.address,
phoneno:this.state.phoneno
}
console.log(user);
axios.post('http://localhost:5000/users/update/'+this.props.match.params.id,user)
.then(res=>console.log(res.data));
this.setState({
username:this.props.username,
address:this.props.address,
phoneno:this.props.phoneno
})
}
render()
{
return (
<div>
<h3>Edit User List</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username: </label>
<input type="text" required
className="form-control"
value={this.state.username}
onChange={this.onchangeUsername}
/>
</div>
<div className="form-group">
<label>Address: </label>
<input type="text" required
className="form-control"
value={this.state.address}
onChange={this.onchangeAddress}
/>
</div>
<div className="form-group">
<label>Phoneno: </label>
<input type="text" required
className="form-control"
value={this.state.phoneno}
onChange={this.onchangePhoneno}
/>
</div>
<div className="form-group">
<input type="submit" value="Update" className="btn btn-primary" />
</div>
</form>
</div>
);
}
}
Prevent your input value to be null.
If you pass from null to not null, you will recieve this error.
A quick fix could be to do this:
<input
type="text"
required
className="form-control"
value={this.state.username || ''}
onChange={this.onchangeUsername}
/>

Setting the default value of an input field after data is retrieved causes the content to overlap and the "onChange" event not to be triggered

I have an "edit category" component in my React application.
The ID is passed through the URL.
When the component is mounted, the action "fetchCategory" is called, which updates the props on the component with the current category.
I have a form which I want to be pre-populated, which I'm currently doing using the defaultValue on the input.
However, this isn't reflected on the state and the label for the text field overlaps the input field.
Any help would be greatly appreciated. I'll leave snippets of my code below which could help with understanding what I'm trying to do.
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchCategory } from "../../store/actions/categoryActions";
class AddOrEditCategory extends Component {
componentDidMount() {
this.props.fetchCategory(this.props.match.params.id);
if (this.props.match.params.id) {
this.setState({
_id: this.props.match.params.id
});
}
}
handleSubmit = e => {
e.preventDefault();
console.log(this.state);
};
handleChange = e => {
this.setState({
[e.target.id]: e.target.value
});
};
render() {
const addingNew = this.props.match.params.id === undefined;
return (
<div className="container">
<h4>{addingNew ? "Add category" : "Edit category"}</h4>
<form onSubmit={this.handleSubmit}>
<div className="input-field">
<input
type="text"
id="name"
defaultValue={this.props.category.name}
onChange={this.handleChange}
/>
<label htmlFor="name">Category name</label>
</div>
<div className="input-field">
<input
type="text"
id="urlKey"
onChange={this.handleChange}
defaultValue={this.props.category.urlKey}
/>
<label htmlFor="urlKey">URL Key</label>
</div>
<button className="btn">{addingNew ? "Add" : "Save"}</button>
</form>
</div>
);
}
}
const mapStateToProps = state => {
return {
category: state.categoryReducer.category
};
};
export default connect(
mapStateToProps,
{ fetchCategory }
)(AddOrEditCategory);
EDIT: Included whole component as requested
You need to replace the 'defaultValue' attribute with 'value' in the inputs.
You are using a controlled vs uncontrolled component. You dont need to use defaultValue.
You can set the initial values on the promise success for fetchCategory
componentDidMount() {
this.props.fetchCategory(this.props.match.params.id).then(response => {
// Set the initial state here
}
}
OR in
componentWillReceiveProps(nextProps) {
// Compare current props with next props to see if there is a change
// in category data received from action fetchCategory and set the initial state
}
React docs
<form onSubmit={this.handleSubmit}>
<div className="input-field">
<input
type="text"
id="name"
onChange={this.handleChange}
value={this.state.name} //<---
/>
<label htmlFor="name">Category name</label>
</div>
<div className="input-field">
<input
type="text"
id="urlKey"
onChange={this.handleChange}
value={this.state.urlKey}
/>
<label htmlFor="urlKey">URL Key</label>
</div>
<button className="btn">{addingNew ? "Add" : "Save"}</button>
</form>

ReactJS Uncaught ReferenceError: onSubmit is not defined

Please help me to understand where I am doing what mistake? I created CustomerForm React Component, which having few form fields. These form fields will add records and in another component will show records into table format.
Every thing is working fine for CustomerForm React Component, but if I am adding onSubmit function than form fields are not loading and I am getting console error as:-
Uncaught ReferenceError: onSubmit is not defined
at new CustomerForm (index.js:32590)
<button type="submit" className="btn btn-primary" onClick={ e => this.onSubmit(e)} > Submit </button>
Also please suggest any better way to write ReactJS code using Props & State...
// Let's import react for creating component
import React from "react";
// Create CustomerForm component
class CustomerForm extends React.Component{
// create constructor function for CustomerForm component
constructor(props){
// call super, so constructor function can connect with CustomerForm component
super(props);
// Use state add object with their property and value
this.state = {
firstName : "",
lastName : "",
phoneNo : "",
issue : "",
}
// Create changeData function
// changeData = e => {
// this.setState({
// [e.target.name] : e.target.value
// });
// };
onSubmit = e => {
e.preventDefault();
console.log(this.state);
}
} // close constructor function
render(){
return(
<form>
<div className="form-group">
<label htmlFor="fname">First name</label>
<input
type="text"
className="form-control"
id="fname"
placeholder="First name"
value={this.state.firstName}
onChange={e => this.setState({ firstName: e.target.value })}
/>
{/* call setState for change firstName value
question - I created changeData function which target name attribute and change value for form fields, but it's not working
onChange={e => this.changeData(e)}
*/}
</div>
<div className="form-group">
<label htmlFor="lname">Last name</label>
<input
type="text"
className="form-control"
id="lname"
placeholder="Last name"
value={this.state.lastName}
onChange={e => this.setState({ lastName: e.target.value })}
/>
{/* call setState for change lastName value */}
</div>
<div className="form-group">
<label htmlFor="phone">Phone no.</label>
<input
type="text"
className="form-control"
id="phone"
placeholder="Phone no."
value={this.state.phoneNo}
onChange={e => this.setState({phoneNo: e.target.value})}
/>
{/* call setState for change phoneNo value */}
</div>
<div className="form-group">
<label htmlFor="issue">Issue</label>
<textarea
className="form-control"
id="issue"
rows="3"
value={this.state.issue}
onChange={e => this.setState({issue: e.target.value})}
>
{/* call setState for change issue value */}
</textarea>
</div>
<button
type="submit"
className="btn btn-primary"
onClick={ e => this.onSubmit(e)}
>
Submit
</button>
</form>
);
}
}
export default CustomerForm;
You're declaring a variable named onSubmit on the constructor and trying to access it with this.onSubmit, like a property.
You can do this in your constructor:
this.onSubmit = e => {
e.preventDefault();
console.log(this.state);
}
The suggestion
A better way to accomplish this is extracting your onSubmit method to a class method, with makes your code more readable and more consistent. Would be something like this:
// Let's import react for creating component
import React from "react";
// Create CustomerForm component
class CustomerForm extends React.Component{
// create constructor function for CustomerForm component
constructor(props){
// call super, so constructor function can connect with CustomerForm component
super(props);
// Use state add object with their property and value
this.state = {
firstName : "",
lastName : "",
phoneNo : "",
issue : "",
}
}
/////////
/// Your submit handler is now a method in the CustomerForm class,
/// so you can access with the keyword "this"
onSubmit(e) {
e.preventDefault();
console.log(this.state);
}
render(){
return(
<form onSubmit={e => this.onSubmit(e)}>
{/* Note that I've changed your handler to form,
is usually better than put on a button, since you're using a form already */}
<div className="form-group">
<label htmlFor="fname">First name</label>
<input
type="text"
className="form-control"
id="fname"
placeholder="First name"
value={this.state.firstName}
onChange={e => this.setState({ firstName: e.target.value })}
/>
{/* call setState for change firstName value
question - I created changeData function which target name attribute and change value for form fields, but it's not working
onChange={e => this.changeData(e)}
*/}
</div>
<div className="form-group">
<label htmlFor="lname">Last name</label>
<input
type="text"
className="form-control"
id="lname"
placeholder="Last name"
value={this.state.lastName}
onChange={e => this.setState({ lastName: e.target.value })}
/>
{/* call setState for change lastName value */}
</div>
<div className="form-group">
<label htmlFor="phone">Phone no.</label>
<input
type="text"
className="form-control"
id="phone"
placeholder="Phone no."
value={this.state.phoneNo}
onChange={e => this.setState({phoneNo: e.target.value})}
/>
{/* call setState for change phoneNo value */}
</div>
<div className="form-group">
<label htmlFor="issue">Issue</label>
<textarea
className="form-control"
id="issue"
rows="3"
value={this.state.issue}
onChange={e => this.setState({issue: e.target.value})}
>
{/* call setState for change issue value */}
</textarea>
</div>
<button
type="submit"
className="btn btn-primary"
>
Submit
</button>
</form>
);
}
}
export default CustomerForm;
Controlled Components
Just one more thing I think it may be helpful to you (I've noted your comment about changeData) so if you not resolve the way to do controlled inputs, this minimalist example may help you, with a onChangeHandler I usually use:
import React from 'react';
export default class MyControlledComponent extends React.Component {
constructor(props){
super(props);
// Initiating the first value for our controlled component
this.state = {
name: ""
}
}
submitHandler(e) {
e.preventDefault();
console.log('Hi, ' + this.state.name + '!');
}
onChangeHandler(e) {
const { name, value } = e.target
/*
Here we using the name property of your input to
increase reuse of this function
*/
this.setState({
[name]: value
});
}
render(){
return (
<div className="my-app">
<form onSubmit={e => this.submitHandler(e)}>
<input type="text"
name="name"
value={this.state.name}
onChange={e => this.onChangeHandler(e)} />
<button>Send!</button>
</form>
</div>
)
}
}
Hope it helps!
Your onSubmit function is not bind either bind it in constructor or use fat arrow properly like
{(return)=>{functionname()}}

react js - how to populate values based on another DOM element value

I have 2 input boxes. Based on one input(1) box value (on key up event), I am populating another input(2) box value. Currently, I am using document.getElementByID option to retrieve element id to populate the values. Is it recommended in react js ? pls suggest. Like to find a better way to to this in react js.
handleChange(e) {
if(document.getElementById("getId").value.length > 4) {
console.log("a")
document.getElementById("getName").value =
document.getElementById("getId").value
}
}
render () {
return (
<div>
<Card>
<div>
<label>Id</label>
<input type="text" id="getId" onKeyUp= {this.handleChange.bind(this)}/>
<div>
<label>Name</label>
<input type="text" id="getName" readOnly/>
</div>
</div>
</Card>
</div>
);
You could store the value of the first input box in your component state and set the value of the second input box to the value from the state.
Then when the value of the input box changes, update the state, using the handleChange method, which in turn re-renders the component updating the second input box.
...
constructor(props) {
super(props)
this.state = {
inputText: ''
}
this.handleChange = this.handleChange.bind(this)
}
handleChange({ target }) {
if (target.value.length > 4) {
this.setState({
inputText: target.value
})
}
}
render () {
return (
<div>
<Card>
<div>
<label>Id</label>
<input type="text" id="getId" onKeyUp={ this.handleChange } />
<div>
<label>Name</label>
<input type="text" id="getName" value={ this.state.inputText } />
</div>
</div>
</Card>
</div>
)
}
...
You can handle issue with two ways.
First way is to use React refs and DOM.
So in code below I have done two things, I have added ref props to getName input and accessed it from handleChange method by this.refs.inputOfName', as well ase.targetas your DOM input without accessing again bygetElementById`.
handleChange(e) {
let value = e.target.value;
if (value.length > 4) {
this.refs.inputOfName.value = value
}
}
render() {
return (
<div>
<Card>
<div>
<label>Id</label>
<input type="text" id="getId" onKeyUp=
{this.handleChange.bind(this)} />
<div>
<label>Name</label>
<input type="text" id="getName" ref="inputOfName" readOnly />
</div>
</div>
</Card>
</div>
);
You can read more about refs here.
Second way is to use states.
I suggest to use states because it's more React "style" approach as well as one of the React advantages, so spend more time learning about state and lifecycle of React.
You can read more about states here.
handleChange(e) {
let value = e.target.value;
if (value.length > 4) {
this.setState({
name: value
});
}
}
render() {
return (
<div>
<Card>
<div>
<label>Id</label>
<input type="text" id="getId" onKeyUp=
{this.handleChange.bind(this)} />
<div>
<label>Name</label>
<input type="text" id="getName" value={this.state.name} readOnly />
</div>
</div>
</Card>
</div>
);
}
As already mention, It's not common to user getElementById within react component, think of what will happen if you will have 2 components rendered.
You can use component state to update your elements.
constructor(props, context) {
super(props, context);
// This will represent your component state to hold current input value.
this.state = { value: "" };
// Do handler bindings in one place and not inside the render
// function as it will create a new function reference on each render.
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({value: e.target.value});
}
render () {
return (
<div>
<Card>
<div>
<label>Id</label>
<input type="text" id="getId" onKeyUp={this.handleChange}/>
<div>
<label>Name</label>
<input type="text" value={this.state.value} readOnly/>
</div>
</div>
</Card>
</div>
);
}

React Modifying Textarea Values

I am working on a project which is basically notepad. I am having problems though updating the <textarea>'s value when an ajax call is made. I tried setting the textarea's value property but then no changes to its value can be made. How can I make it so on a state change the textarea's value changes and can be edited.
The code I have is as follows.
In the parent class
<Editor name={this.state.fileData} />
In the Editor class
var Editor = React.createClass({
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.props.name}></textarea>
<input type="submit" value="Save" />
</form>
);
}
});
I can't use defaultValue because the value of the textarea is not known on page load and when I try and put the data between the textareas nothing happens. I would like it to take the state value whenever the state changes but have it editable in between.
Thanks
Edit
I managed to get it working using jQuery but would like to do it in React instead, I called this before render:
$('#noter-text-area').val(this.props.name);
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.
The value of the following uncontrolled textarea cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea can be changed because of how
value is mapped to a state as well as the onChange event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"

Resources