function keyword in class based component and inChange event - reactjs

Can anyone please help me understand if there's any issue with the below code snippet:
import React, { Component } from "react";
class AddContactForm extends Component {
constructor() {
super();
this.state = {
name: "",
email: "",
number: ""
}
}
handleOnChange(event) {
console.log("Hi");
console.log(event.target.id);
console.log(event.target.value);
}
render() {
return (
<React.Fragment>
<div className="mx-auto">
<div class="mb-3 row">
<label for="username" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" onChange={this.handleOnChange.bind(this)}/>
</div>
</div>
<div class="mb-3 row">
<label for="mobileNumber" class="col-sm-2 col-form-label">Mobile Number</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="mobileNumber" onChange={this.handleOnChange}/>
</div>
</div>
<div class="mb-3 row">
<label for="emailId" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="emailId" onChange={this.handleOnChange}/>
</div>
</div>
<button className="btn btn-primary w-25">Add</button>
</div>
</React.Fragment>
)
}
}
export default AddContactForm;
I am facing the problems below:
1 - unable to use function keyword with handleOnChange method
2 - none of my inputs are firing the onChange event. I am unable to get any logs in the console as added in HandleOnChange method.
Thanks.

In your constructor bind all the methods.
constructor() {
super();
this.state = {
name: "",
email: "",
number: ""
}
this.handleOnChange: this.handleOnChange.bind(this)
}
And in your inputs use like this
<input onClick={this.handleOnChange} />

You have few errors in your code aside from the one #Muhammad pointed out, some attribute names were altered in to avoid conflict for jsx so:
class became className
for became htmlFor with the label element a similar problem here.
It's also worth noting that, using arrow function is favored over using bind, so you create the function normally as an arrow function.
handleOnChange = (event) => {
console.log("Hi");
console.log(event.target.id);
console.log(event.target.value);
};
and make onChange call it.
onChange={this.handleOnChange}
You can refer for this codesandbox for a demo, you may also want to read these two questions here:
correct-use-of-arrow-functions-in-react
how-to-avoid-bind-or-inline-arrow-functions-inside-render-method

Related

Unable to add data from form to variable using REACT

We're trying to set up a data entry form that adds input to an object in mongo. We're positive this has to do with our front end as we can't get the input data to even print to an alert.
import { Panel, Button,ButtonToolbar} from 'react-bootstrap';
export default class ResearcherPortal extends React.Component {
constructor(props){
super(props);
this.state = {
schoolName: '',
studyName: '',
studyDescription: '',
identifier: '',
numberOfConsenting: null,
numberOfNonconsenting: null
},
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
this.setState({numberOfConsenting: event.target.value});
alert(this.state.numberOfConsenting);
}
render() {
return (
<div className="jumbotron">
<div className="container ">
<div className ="row justify-content-md-center">
<Panel bsStyle="primary">
<Panel.Heading>
<h2>Researcher Portal</h2>
</Panel.Heading>
<Panel.Body>
<form id="Account Creation" action={"/researcherPortal"} method="POST">
<div className="form-group">
<input type="text" className="form-control" id="schoolName" placeholder="School Name"/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="studyName" placeholder="Study Name"/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="studyDescription" placeholder="Study Description"/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="identifier" placeholder="Unique Identifier"/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="numberOfConsenting" placeholder="Number of Consenting Students" value={this.state.numberOfConsenting}/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="numberOfNonconsenting" placeholder="Number of Nonconsenting Students"/>
</div>
<Button type="submit" className="btn btn-primary" onClick={this.handleSubmit.bind(this)}>Create Accounts</Button>
</form>
</Panel.Body>
</Panel>
</div>
</div>
</div>
);
}
}
Expected result is the input for "Number of Consenting Students", however we are just outputting the initial constructor value.
You need to provide an onChange to the input whose value is this.state.numberOfConsenting. Something like -
changeNumberOfConsenting(event) {
this.setState({ numberOfConsenting: event.target.value });
}
...
<input ... value={this.state.numberOfConsenting} onChange={this.changeNumberOfConsenting} />
and then bind it in your constructor like you did for handleSubmit.
Use refs.
Add handler to constructor:
this.consentingStudents = React.createRef();
Add this ref for needed input:
<input type="text" className="form-control" id="numberOfConsenting" placeholder="Number of Consenting Students" ref={this.consentingStudents} value={this.state.numberOfConsenting} />
And get its value in the handleSubmit():
handleSubmit(event) {
this.setState({ numberOfConsenting: this.consentingStudents.current.value });
alert(this.consentingStudents.current.value);
}

react state change doesn't work as expected

Hi this is a code that I tried out to submit data from a form.
import * as React from 'react'
export class User extends React.Component{
constructor(props) {
super(props);
this.state = {
name: '',
message: '',
messages: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div class="panel panel-default" id="frame1" onSubmit={this.handleSubmit}>
<form class="form-horizontal" action="/action_page.php">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Your Name </label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" placeholder="Enter your Name" onChange={this.handleChange} />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="message" placeholder="Enter your Message" onChange={this.handleChange}/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
);
}
handleChange(evt) {
this.setState({ [evt.target.name]: evt.target.value });
}
handleSubmit(event) {
this.setState({ messages: this.state.message });
alert('A name was submitted: ' + this.state.name + ' jjjjjj' + this.state.messages);
event.preventDefault();
}
}
As you can see in the handleSubmit(event) method, I'm setting the value of message to messages. But when I try to print messages, no value has been set. What is the mistake I'm doing here. Isn't this value need to be printed
setState is asynchronous. Try this:
handleSubmit(event) {
event.preventDefault();
this.setState({ messages: this.state.message }, () => {
alert('A name was submitted: ' + this.state.name + ' jjjjjj' + this.state.messages);
});
}
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.
https://reactjs.org/docs/react-component.html#setstate

Showing input value in the url link (ReactJs Laravel)

I created laravel project with the reactjs framework and I'm new for this framework. I have problem and why It happens every time i submit the form.
Goal: users can register through online
Problem:
Why it happens when i submit the button the input value of user shown in the url link?
The data that I input is not inserted to the database.
Code:
constructor() {
super();
this.state = {
f_name:'',
l_name:'',
m_name:'',
email:'',
home_num:'',
contact_num:'',
Job_name:[],
employ_status:'',
employ_relocate:'',
employ_start_date:'',
employ_file:''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handle_fname = this.handle_fname.bind(this);
this.handle_lname = this.handle_lname.bind(this);
this.handle_mname = this.handle_mname.bind(this);
this.handle_email = this.handle_email.bind(this);
this.handle_homenum = this.handle_homenum.bind(this);
this.handle_contactnum = this.handle_contactnum.bind(this);
this.handle_employ_status = this.handle_employ_status.bind(this);
this.handle_employ_relocate = this.handle_employ_relocate.bind(this);
this.handle_employ_start_date = this.handle_employ_start_date.bind(this);
this.handle_employ_file = this.handle_employ_file.bind(this);
}
componentDidMount() {
const id = this.props.match.params.id;
axios.get('/api/online_application_job_title/' +id).then(response => {
this.setState({
Job_name:response.data
})
})
}
handleSubmit(e)
{
const data = {
firstname: this.state.f_name,
lastname : this.state.l_name,
middlename : this.state.m_name,
email : this.state.email,
home_number : this.state.home_num,
contact_num : this.state.contact_num,
job : this.state.Job_name[0].position_name,
employ_status : this.state.employ_status,
employ_relocate : this.state.employ_relocate,
employ_start_date : this.state.employ_start_date,
employ_file : this.state.employ_file
}
axios.post('/api/save_application',data).then(response => {
console.log(response);
}).catch(error => console.log(error));
}
handle_fname(e)
{
this.setState({
f_name:e.target.value,
})
}
handle_lname(e){
this.setState({
l_name:e.target.value,
})
}
handle_mname(e){
this.setState({
m_name:e.target.value,
})
}
handle_email(e){
this.setState({
email:e.target.value,
})
}
handle_homenum(e){
this.setState({
home_num:e.target.value
})
}
handle_contactnum(e){
this.setState({
contact_num:e.target.value
})
}
handle_employ_status(e){
this.setState({
employ_status:e.target.value
});
}
handle_employ_relocate(e){
this.setState({
employ_relocate:e.target.value,
})
}
handle_employ_start_date(e){
this.setState({
employ_start_date:e.target.value,
})
}
handle_employ_file(e){
this.setState({
employ_file: e.target.files[0].extension
})
}
renderName() {
return (
this.state.Job_name.map(name => (
<input placeholder="" value={name.position_name} type="text" className="form-control"/>
))
)
}
render() {
return (
<div>
<div className="header">
<div className="jumbotron">
<h1>Online Application</h1>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<div className="container">
<h5><b>Personal Info</b></h5>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="First Name*"
value={this.state.f_name}
onChange={this.handle_fname}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Last Name*"
value={this.state.l_name}
onChange={this.handle_lname}
className="form-control"/>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="Middle Name*"
value={this.state.m_name}
onChange={this.handle_mname}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Email Address*"
type="email"
value={this.state.email}
onChange={this.handle_email}
className="form-control"/>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="Home Number*"
type="number"
value={this.state.home_num}
onChange={this.handle_homenum}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Contact Number*"
type="number"
value={this.state.contact_num}
onChange={this.handle_contactnum}
className="form-control"/>
</div>
</div>
<br/><br/>
<h5><b>Employment Application</b></h5>
<br/>
<div className="row">
<div className="col-md-6">
<p>Position Applying For</p>
{this.renderName()}
</div>
<div className="col-md-6">
</div>
</div>
<br/><br/>
<div className="row">
<div className="col-md-6">
<p>1. What is your current employment status?</p>
<div className="form-check-inline">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Unemployed"/>Unemployed
</label>
</div>
<div className="form-check-inline">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Employed"/>Employed
</label>
</div>
<div className="form-check-inline disabled">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Self-Employed"/>Self-Employed
</label>
</div>
<div className="form-check-inline disabled">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Student"/>Student
</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>2. Are you willing to relocate?</p>
<div className="form-check-inline">
<label className="form-check-label">
<input type="radio"
name="relocate"
onChange={this.handle_employ_relocate}
className="form-check-input"
value="Yes"/>Yes
</label>
</div>
<div className="form-check-inline">
<label className="form-check-label">
<input type="radio"
name="relocate"
onChange={this.handle_employ_relocate}
className="form-check-input"
value="No"/>No
</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>3. When is your available start date?</p>
<input
name="startdate"
type="date"
onChange={this.handle_employ_start_date}
value={this.state.employ_start_date}
required=""
className="form-control"/>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>4. Kindly attach a copy of your resume (PDF,docx files only).</p>
<div className="custom-file">
<input
type="file"
name="file"
accept="application/msword,application/pdf"
onChange={this.handle_employ_file}
className="custom-file-input"
id="inputGroupFile04"/>
<label className="custom-file-label" htmlFor="inputGroupFile04">Choose file</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
className="btn btn-outline-primary btn-large form-control col-md-5"
type="submit"
value="Send Application"/>
</div>
<div className="col-md-6"></div>
</div>
</div>
</form>
</div>
)
}
Controller:
public function save_application(Request $request)
{
$firstname = $request->get('firstname');
$lastname = $request->get('lastname');
$middlename = $request->get('middlename');
$email = $request->get('email');
$home_number = $request->get('home_number');
$contact_num = $request->get('contact_num');
$job = $request->get('job');
$employ_status = $request->get('employ_status');
$employ_relocate = $request->get('employ_relocate');
$employ_start_date = $request->get('employ_start_date');
$employ_file = $request->get('employ_file');
$now = new DateTime();
DB::insert('INSERT INTO onlineapplication
(position_name,firstname,middlename,lastname,email,homenumber,phonenumber,employmentstatus,relocate,starting_date,destination,file_img_name,Status)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',[
$firstname,
$lastname,
$middlename,
$email,
$home_number,
$contact_num,
$job,
$employ_status,
$employ_relocate,
$employ_start_date,
$employ_file
]);
return response()->json('Successfully inserted');
}
When form tag is used, the submit will trigger the default behaviour that is based on the method provided and the action url.
as in your example you are handling the data explicitly you should prevent the default behaviour.
add the below code in handle submit
handleSubmit(e) {
e.preventDefault();
...
...
}
this will prevent the default behaviour.
Improvement for state update:
you don't need individual functions to update the input value to state this can be combined in one function.
to combine, provide the input name same as state name.
this.state ={
"f_name": '',
"l_name": '',
...
}
<input name="f_name" ... onChange={this.handleInputChange}/>
<input name="l_name" .. onChange={this.handleInputChange}/>
handleInputChange(e){
let target = e.target;
let name = target.name;
let value = target.value
this.setState({[name]: value})
}
for more info refer this link.
First, I just want to introduce to you to the arrow function in JavaScript (ES6). Declaring private methods like this:
handle_fname = (e) =>
{
this.setState({
f_name:e.target.value,
})
}
will save you time from unnecessary binding in the constructor.
Regarding your question, you missed to show the content of your this.handleSubmit(). Without this, I can assume that the form submit fired a get call since you failed to put method attribute in your <form/> tag, and without indicating your method attribute will result to default get method. Get method when used, data submitted will be visible in the page address field of your browser.
EDIT
You already added your handleSubmit() in your question, and it looks okay. If data is still shown in the address field of your browser, try adding method="post" in your form tag like this:
<form onSubmit={this.handleSubmit} method="post">

React bind custom handler onChange to input

This is my SearchForm.js, it creates form with two inputs keywords and city and select list date
import React from 'react';
import ReactDOM from 'react-dom';
class SearchForm extends React.Component {
constructor(props) {
super(props)
this.state = {
keywords: '',
city: '',
date: ''
}
//this.handleChange = this.handleChange.bind(this)
//this.handleSubmit = this.handleSubmit.bind(this)
this.handleKeywordsChange = this.handleInputChange.bind(this);
}
handleKeywordsChange(event) {
console.log(1);
}
render() {
return (
<form className='form search-form' onSubmit={this.handleSubmit}>
<div class="form-row">
<div class="form-group col-md-5">
<label for="keywords">Keywords</label>
<input type="text" class="form-control" name="keywords" id="keywords" placeholder="Keywords" onChange={this.handleKeywordsChange} value={this.state.name} />
</div>
<div class="form-group col-md-5">
<label for="city">City</label>
<input type="text" class="form-control" name="city" id="city" placeholder="City" onChange={this.handleChange} value={this.state.name} />
</div>
<div class="form-group col-md-2">
<label for="date">Date</label>
<select class="form-control" name="date" id="date" onChange={this.handleChange} value={this.state.value}>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<input id='formButton' className='btn btn-primary' type='submit' placeholder='Send' />
</div>
</div>
</form>
)
}
}
export { SearchForm }
and I need to add different handle function to inputs like handleKeywordsChange, but there are some errors
What's wrong with my bind ?
I think there is a typo in
this.handleKeywordsChange = this.handleInputChange.bind(this);
Have you tried change it to
this.handleKeywordsChange = this.handleKeywordsChange.bind(this);
Error is because of this:
this.handleKeywordsChange = this.handleInputChange.bind(this);
You need to define handleInputChange, instead of handleKeywordsChange:
handleInputChange () {
}
Reason is as per MDN Doc:
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
So in handleKeywordsChange method you are just storing the reference of function returned by bind. So the actual function will be handleInputChange and that you need to define.

Setting a state in react.js with two-way binding

i'am working in a project using react.js and fire-base, i have a form when i set the input with my state that is fill with data of fire-base, and is working i can update and create new registry, but i think that my onChangeHandle() for the inputs is not the correct way to do it.
This is my form:
render(){
return (
<div className="row">
<div className="col-xs-3 col-sm-3 col-md-3 col-lg-3"></div>
<div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<div className="form-group">
<label >Nombre de Proyecto</label>
<input type='text' value={this.state.proyectName} onChange={(event)=>this.onChangeHandle('p',event)}className="form-control" id="project_name"/>
</div>
<div className="form-group">
<label >Inspiracion</label>
<textarea value={this.state.inspiration} onChange={(event)=>this.onChangeHandle('i',event)} rows="4" cols="50" className="form-control" id="inspiration"/>
</div>
<div className="form-group">
<label >Que problema resuelve</label>
<textarea value={this.state.whatDoes} onChange={(event)=>this.onChangeHandle('w',event)} rows="4" cols="50" className="form-control" id="what_does"/>
</div>
<div className="form-group">
<label >Como esta hecho</label>
<textarea value={this.state.howBuild} onChange={(event)=>this.onChangeHandle('h',event)} rows="4" cols="50" className="form-control" id="how_build"/>
</div>
<div className="form-group">
<label >Integrantes</label>
<input type='text' className="form-control" id="team"/>
</div>
<div className="form-group">
<button className="form-control btn btn-primary" onClick={()=>this.writeStartupData()} >Agregar </button>
</div>
</div>
</div>
)
}
And here is my event handler:
onChangeHandle(exp,event){
switch(exp){
case "p":
this.setState({
proyectName: event.target.value,
});
break;
case "i":
this.setState({
inspiration: event.target.value,
});
break;
case "w":
this.setState({
whatDoes: event.target.value,
});
break;
case "h":
this.setState({
howBuild: event.target.value,
});
break;
case "t":
this.setState({
team: event.target.value,
});
break;
}
}
I think you should do something like this.
<div className="form-group">
<label >something</label>
<input
type='text'
value={this.state.something}
onChange={event => this.setState({something: event.target.value})}
className="form-control" id="project_name"/>
</div>
The code for your event handlers is not something I'd consider very readable, DRY, or adherent to any react best practises.
Using an anonymous arrow function and calling setState from there, like #vitaliy-andrianov has done, is perfectly fine. There is just one downside with arrow functions in that case: the functions are re-created on every re-render, incurring a small (most likely negligible) performance penalty. It could also be a little more dry. Below is another acceptable alternative:
// Component class method
handleFormChange(event) {
this.setState({
[event.currentTarget.name]: event.currentTarget.value
});
}
// ... and if you like destructuring
handleFormChange({currentTarget: {name, value}}) {
this.setState({ [name]: value });
}
// An example input
<input
className="form-control"
name="proyectName"
type="text"
value={this.state.proyectName}
onChange={this.handleFormChange} />
Note: I am passing handleFormChange directly to the onChange prop; for this to work, the function has to be bound to the scope of the class. So make sure you do that in the constructor (this.handleFormChange.bind(this)), or just use an arrow function.

Resources