ReactJs submitting form data to the screen - javascript

I want a way to submit a form in ReactJs to the browser.
var ToDoForm = React.createClass({
getInitialState: function() {
return {text: ''};
},
handleChange: function(event) {
this.setState({text: event.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
return (
<h2> hey </h2>
)
},
render: function() {
return (
<div>
<h1> todos </h1>
<form className="todoForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Type out a task"
value={this.state.text}
onChange={this.handleChange}
/>
<input
type="submit"
value="Submit todo"
/>
</form>
</div>
);
}
});
I have a function handleSubmit that I want when the form is submitted to just print the word hey in the browser as a heading2. I know this is not very wise or makes any sense but I just want to see it working and then I'll it to return something that makes more sense. So far when I click on the submit button, nothing happens. any solutions?
also worth adding, this question (Get form data in Reactjs). I want what this guy is basically doing but instead of console.logs an actual print to screen, just to clarify if I have been unclear

Use a state to handle it ? Something like
getInitialState: function(){
return{
submitted: false
},
handleSubmit: function(e){
e.preventDefault();
this.setState({ subbmitted: true});
},
render: function(){
return (
<div>
<h1> todos </h1>
{!!this.state.submitted ?
<div>
<h2> {'Hey'} </h2>
</div>
:
<form className="todoForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Type out a task"
value={this.state.text}
onChange={this.handleChange}
/>
<input
type="submit"
value="Submit todo"
/>
</form>
</div>
)

Related

Form validation with NuxtJS

I'm new to NuxtJS, I was trying to do a simple form to try things out.
The idea is that I have a component that contains the full form
<template>
<div>
<h1>
{{ title }}
</h1>
<form #submit.prevent="handleSubmit">
<input type="email" v-model="email" />
<input type="password" v-model="password" />
<button type="submit">Sign in</button>
</form>
</div>
</template>
<script>
export default {
data: function() {
return {
title: 'Sign in',
email: null,
password: null
}
},
methods: {
handleSubmit: function() {
console.log('Hello')
}
}
}
</script>
It's nothing crazy, and then I'm just calling this component in my page
<template>
<LoginForm />
</template>
<script>
export default {
}
</script>
But when I submit my form I can't see my message in the console, I'm wondering what I did wrong or did I miss something ?
Also it is a good practice to make a component like this or should I divide more my component into small one's ?

How to use onchange on 2 input fields in React

I am trying to catch 2 input field's value but none of the input fields is working.
when I comment second Input field than the first one works properly.
state = { zipcode: null, city: "" };
onFormSubmit = event => {
event.preventDefault();
//Callback
this.props.onEnter(this.state.zipcode);
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="number"
className={`form-control`}
placeholder="Enter ZIP code"
name="zipcode"
onChange={this.handleChange} />
<input
type="text"
className={`form-control`}
placeholder="Enter Zip-code"
name="city"
onChange={this.handleChange}/>
</form>
</div>
);
}
}
When I hit enter after entering a query in the first input field I get no output and no error.
I tried below code and it worked just fine. Maybe there is something wrong with your callback function. Because on form submission you are getting the correct values.
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
zipcode: null,
city: ""
}
}
onFormSubmit = event => {
event.preventDefault();
//Callback
console.log(this.state);
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="number"
className={`form-control`}
placeholder="Enter ZIP code"
name="zipcode"
onChange={this.handleChange} />
<input
type="text"
className={`form-control`}
placeholder="Enter Zip-code"
name="city"
onChange={this.handleChange}/>
<input type="submit" value="submit" />
</form>
</div>
);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
Here is the jsfiddle link with your code. Check in the inspect element after clicking on the submit button.
It works.
https://jsfiddle.net/t4o0xawr/1/

Text input unfocused after one character React?

var uuid = require('uuid-v4');
// Generate a new UUID
var myUUID = uuid();
// Validate a UUID as proper V4 format
uuid.isUUID(myUUID); // true
var questionNum = 0;
class App extends Component {
constructor(props){
super(props);
this.state = {
key: uuid(),
title: "",
author: "",
questions: [],
answers: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
addQuestion = () => {
questionNum++;
this.setState({
questions: this.state.questions.concat(["question","hi"])
});
console.log(this.state.questions);
this.setState({
answers: this.state.answers.concat(["hello","hi"])
});
console.log(this.state.answers);
console.log(questionNum);
console.log(this.state.title);
console.log(this.state.author);
}
render() {
return (
<div className="App">
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Quiz Form 2.0</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
<div>
<form>
<div className="Intro">
Give your Quiz a title: <input type="text" value={this.state.title} onChange={this.handleChange} name="title" key={uuid()}/><br/>
Who's the Author? <input type="text" value={this.state.author} onChange={this.handleChange} name="author" key={uuid()}/><br/><br/>
</div>
<div className="questions">
Now let's add some questions... <br/>
{this.addQuestion}
</div>
</form>
<button onClick={this.addQuestion}>Add Question</button>
</div>
</div>
);
}
}
export default App;
Both of the inputs on my page unfocus after typing only one character. Here's my code, I'm not entirely sure where I am going wrong here, it all worked just fine yesterday.
If there is anything else that you need to know just leave a comment and I will get to it. Your help is much appreciated, thanks!
When the key given to a component is changed, the previous one is thrown away and a new component is mounted. You are creating a new key with uuid() every render, so each render a new input component is created.
Remove the key from your inputs and it will work as expected.
<div className="Intro">
Give your Quiz a title:
<input
type="text"
value={this.state.title}
onChange={this.handleChange}
name="title"
/>
<br/>
Who's the Author?
<input
type="text"
value={this.state.author}
onChange={this.handleChange}
name="author"
/>
<br/><br/>
</div>
Tholle's response is correct. However, you should make some adjustments to how you interact with state. I've reworked your code with comments and included the uuid fix.
class App extends Component {
constructor(props){
super(props);
this.state = {
title: "",
author: "",
questions: [],
answers: []
}
this.handleChange = this.handleChange.bind(this);
this.addQuestion = this.addQuestion.bind(this);
}
handleChange({ target }) {
// since you'll always have a synthetic event just destructure the target
const { checked, name, type, value } = target;
const val = type === 'checkbox' ? checked : value;
this.setState({
[name]: val
});
}
addQuestion() {
// never modify state directly -> copy state and modify
const { answers, questions } = Object.assign({}, this.state);
// update your answers
answers.push(["hello", "hi"]);
// update your questions
questions.push(["question", "hi"]);
// now update state
this.setState({
answers,
questions
}, () => {
console.log(this.state);
});
}
render() {
return (
<div className="App">
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Quiz Form 2.0</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
<div>
<form>
<div className="Intro">
Give your Quiz a title: <input type="text" value={this.state.title} onChange={this.handleChange} name="title" /><br/>
Who's the Author? <input type="text" value={this.state.author} onChange={this.handleChange} name="author" /><br/><br/>
</div>
<div className="questions">
Now let's add some questions... <br/>
{this.addQuestion}
</div>
</form>
<button onClick={this.addQuestion}>Add Question</button>
</div>
</div>
);
}
}
export default App;

How do I get onChange to work with several form fields in Reactjs?

I'm trying to get this form to work, but when I try to type into the form fields, nothing happens.
At first, the text that I would input would appear on the fields simultaneously, and then I changed a couple things.
Now it does not work at all...
I'm thinking that it is an issue with onChange, but I'm not sure.
Here is the code:
handleChange = (event) => {
let newState = {};
newState[event.target.name] = event.target.value;
this.setState(newState);
}
handleSubmit = (event) => {
event.preventDefault();
this.setState({
title: '',
description: '',
dueDate: '',
assignee: '',
items: [...this.state.items, this.state.title, this.state.description,
this.state.dueDate, this.state.assignee]
});
}
render() {
return (
<div>
<button onClick={this.openModal}>Add a Task</button>
<ReactModal
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
>
<div className='modalDialog'>
<form className="App" onSubmit={this.handleSubmit}>
Title: <input value={this.state.title} onChange={this.handleChange} />
Description: <input value={this.state.description} onChange={this.handleChange} />
Due Date: <input value={this.state.dueDate} onChange={this.handleChange} />
Assignee: <input value={this.state.assignee} onChange={this.handleChange} />
<button>Submit</button>
</form>
<button onClick={this.closeModal}>X</button>
</div>
</ReactModal>
<List items={this.state.items} />
</div>
);
}
}
const List = props => (
<ul>
{props.items.map((item,index) => <li key={index}>{item}</li>)}
</ul>
);
export default App;
Thanks for the help!
Your code should work well beside one little thing that is missing.
In your change handler your using event.target.name but you are missing the name attribute on those <input /> elements.
For example:
Title: <input name="title" value={this.state.title} onChange={this.handleChange} />
title attribute should be corresponding to the property on the state of course.
I suspect the problem is that your element does not have type="submit", so the form never submits. The onChange events are probably firing correctly (although as bennygenel points out, the input fields should have a "name" attribute to make your state changes work!)

Form Submit using reactjs

I am new in reactjs. I am creating a sample project using reactjs. First I am getting error like state is null. After setting intial state i am getting error
I got Warning: valueLink prop on input is deprecated; set value and onChange instead
I know there are many question related to this but my problem is not solved please help.
Here is code:
import React, {Component} from 'react';
import {Link} from 'react-router'
import validator from 'validator';
import LinkedStateMixin from 'react-addons-linked-state-mixin';
module.exports = React.createClass({
mixins: [LinkedStateMixin],
getInitialState() {
return {};
},
saveData: function(){
//console.log(this.state)
},
render () {
return (
<form>
<div className="page-content container">
<div className="row">
<div className="col-md-4 col-md-offset-4">
<div className="login-wrapper">
<div className="box">
<div className="content-wrap">
<h6>Sign Up</h6>
<input className="form-control" name ="email" placeholder="E-mail address" type="text" valueLink={this.linkState('email')}/>
<input className="form-control" name="password" placeholder="Password" type="password"/>
<input className="form-control" placeholder="Confirm Password" type="password" />
<div className="action">
<button type="button" className ="btn btn-primary signup" onClick={this.saveData}>Sign Up</button>
</div>
</div>
</div>
<div className="already">
<p>Have an account already?</p>
<Link to ="/reactApp/">Login</Link>
</div>
</div>
</div>
</div>
</div>
</form>
)
}
});
Please read more about the fundamentals of React and handling state in forms in the React documentation. No mixins or anything complicated required. Also as stated above "ReactLink is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using ReactLink."
Each of your text inputs should have a change handler just like the error message says... There are many ways you could accomplish this but below is a basic example. Check out the snippet below in a fiddle here https://jsfiddle.net/09623oae/
React.createClass({
getInitialState: function() {
return({
email: "",
password: "",
passwordConfirmation: ""
})
},
submitForm: function(e) {
e.preventDefault()
console.log(this.state)
},
validateEmail: function(e) {
this.setState({email: e.target.value})
},
validatePassword: function(e) {
this.setState({password: e.target.value})
},
confirmPassword: function(e) {
this.setState({passwordConfirmation: e.target.value})
},
render: function() {
return (
<form onSubmit={this.submitForm}>
<input
type="text"
value={this.state.email}
onChange={this.validateEmail}
placeholder="email"
/>
<input
type="password"
value={this.state.password}
onChange={this.validatePassword}
placeholder="password"
/>
<input
type="password"
value={this.state.passwordConfirmation}
onChange={this.confirmPassword}
placeholder="confirm"
/>
</form>
)
}
});
Solution
You cannot use valueLink anymore, instead use onChange react event to listen for input change, and value to set the changed value.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'Hello!'};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
);
}
Clarification
Notice that since the value is set from a state, it will only get updated from changing the attached state, writing in the input does nothing, unless you listen for the input changed (via onChange event) and update the state accordingly.
source: from React documentation
You should set your state to atleast empty initially, if you want to access it at a later point of time. Something similar to below will do
getInitialState() {
return {};
},
ReactLink Without valueLink
You can change with
<input type="text" value={valueLink.value} onChange={handleChange} />
Reference:
https://facebook.github.io/react/docs/two-way-binding-helpers.html
This warning happens because the React Link was deprecated in React 0.15:
ReactLink is deprecated as of React v15. The recommendation is to
explicitly set the value and change handler, instead of using
ReactLink.
So, instead of use this.linkState('email') and valueLink:
<input className="form-control"
name ="email"
placeholder="E-mail address"
type="text"
valueLink={this.linkState('email')}/>
Use this.state.email and an onChange function:
callThisWhenChangeEmail: function(emailFromInput) {
this.setState({
email: emailFromInput
});
},
render () {
/* the existent code above */
<input className="form-control"
name ="email"
placeholder="E-mail address"
type="text"
value={this.state.email}
onChange={this.callThisWhenChangeEmail}/>
/* the existent code below */
}
When the user type some e-mail in the input, the function callThisWhenChangeEmail is called, receiving the e-mail as parameter (emailFromInput). So, you only need to set this e-mail in the state.

Categories

Resources