might seem awkward right, but i simply did equalize the value attribute of input tag into some random state. but i simply cant even type into the input. the input is supposed to be emptied after click but well, nothing is happening. (sorry if this question is asked before, im really going crazy and couldnt find anything on google which helps me)
import React from 'react';
import './App.css';
class App extends React.Component{
constructor(){
super()
this.state ={
address : "",
name:"",
main : {
},
// city:undefined,
inputval: "",
}
}
handleName = (event) => {
this.setState({name: event.target.value})
}
handleAdd = (event) => {
this.setState({address: event.target.value})
}
handleClick = (event) => {
event.preventDefault()
this.setState({main:{
address: this.state.address,
name: this.state.name,
}})
this.setState({inputval:""})
}
render(){
return(
<div>
<form>
<input value={this.state.inputval} type="text" onChange={(e) => {this.handleName(e)}}/>enter full name
<br/>
<input value={this.state.inputval} type="text" onChange={(e) => {this.handleAdd(e)}}/> enter adresss
<br/>
<button onClick={(e) => {this.handleClick(e)}}>Click me</button>
</form>
</div>
)
}
}
export default App;
import React from "react";
class App extends React.Component {
constructor() {
super();
this.state = {
address: "",
name: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
alert("A name was submitted: " + this.state.name);
this.setState({
address: "",
name: ""
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
value={this.state.name}
name="name"
type="text"
onChange={this.handleChange}
/>
enter full name
<br />
<input
value={this.state.address}
name="address"
type="text"
onChange={this.handleChange}
/>{" "}
enter adresss
<br />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default App;
Add name attributes to write only one change handler. It makes it so easier. I hope it helps. Look I wrote again setState to reset after submitting
You are not changing inputval at all. If you want to reset the form after button change. Then below is the solution
import React from 'react';
import './App.css';
class App extends React.Component{
constructor(){
super()
this.state ={
address : "",
name:"",
main : {
},
// city:undefined,
inputval: "",
}
this.handleName = this.handleName.bind(this)
this.handleAdd = this.handleAdd.bind(this)
this.handleClick = this.handleClick.bind(this)
}
handleName = (event) => {
this.setState({name: event.target.value})
}
handleAdd = (event) => {
this.setState({address: event.target.value})
}
handleClick = (event) => {
event.preventDefault()
this.setState({main:{
address: this.state.address,
name: this.state.name,
}})
this.setState({
address: "",
name: ""
})
}
render(){
return(
<div>
<form>
<input value={this.state.name} type="text" onChange={(e) => {this.handleName(e)}}/>enter full name
<br/>
<input value={this.state.address} type="text" onChange={(e) => {this.handleAdd(e)}}/> enter adresss
<br/>
<button onClick={(e) => {this.handleClick(e)}}>Click me</button>
</form>
</div>
)
}
}
export default App;
Related
I am quite new in React and I've been stuck in this problem. When I send email address to mailchimp, I have still this address after sending. I tried to fix it but it's just a mess.
class Newsletter extends React.Component {
constructor(props) {
super(props);
this.state = {
email: ''
};
mySubmitHandler = (event) => {
event.preventDefault();
this.setState({email: ''});
}
render() {
return (
<form className="newsletter_form" onSubmit={this.mySubmitHandler} value={this.state.email}>
<h1 style={{fontSize: 40, paddingTop: '10px'}}>Newsletter</h1>
<p className="newsletter_info">Stay up to date with dance news in Oslo with us</p>
<MailchimpSubscribe value="subscribe" url={process.env.REACT_APP_MAILCHIMP_URL} />
<p className="newsletter_info">Your email is safe with us.</p>
<p className="newsletter_info"> We don't spam.</p>
</form>
)
}
};
export default Newsletter;
I fixed this problem by adding:
class Newsletter extends React.Component {
constructor(props) {
super(props);
this.state = {
email: ''
};
}
mySubmitHandler = (event) => {
event.preventDefault();
event.target.reset();
}
render() {
return (
<form className="newsletter_form" onSubmit={this.mySubmitHandler.bind(this)}>
but thanks! :)
By using a good tool for handling form data you can have a more readable and clean code.
import React from "react";
import { useForm } from "react-hook-form";
const Newsletter App() {
const {
reset, register, handleSubmit, formState: { errors }
} = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<button type="button" onClick={reset}>x</button>
<input defaultValue="test" {...register("example")} />
<input {...register("exampleRequired", { required: true })} />
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
export default Newsletter;
Here is my simple to-do app program where I have made only one component which takes in the input form user and passes that input value to App.js to update items in App.js state.
todo-form.component.js
import React from 'react';
class SignInForm extends React.Component {
constructor(){
super();
this.state ={
temp: null
};
}
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value
},
console.log(this.state)
);
// this.props.addInput(e.target.value);
}
handleSubmit= (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
}
render(){
return(
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;
App.js
import React from 'react';
import './App.css';
import SignInForm from './components/todo-form/todo-form.component'
import ItemList from './components/todo-list/todo-list.component';
class App extends React.Component {
constructor(){
super();
this.state = {
input: []
};
}
addInput = (item) => {
let newInput=[...this.state.input,item];
console.log(newInput);
this.setState = ({
input: newInput
},
console.log(this.state)
);
}
render(){
return (
<div className="App">
<h1>TO-DO LIST</h1>
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
On taking input the state inside todo-form.component.js is getting updated with the typed input value but on passing state.temp in handleChange function, the state inside App.js is not updating when addInput function is called.
Please help me on this issue and how my state is not getting updated in App.js??
Your setState is the problem. Have a look at my code.
App.js
class App extends React.Component {
state = {
input: [],
};
addInput = (item) => {
let newInput = [...this.state.input, item];
//setState should be this way
this.setState({
input: newInput,
});
};
render() {
return (
<div className="App">
<h1>TO-DO LIST</h1>
{this.state.input.map((el) => (
<li> {el}</li>
))}
<SignInForm addInput={this.addInput} />
</div>
);
}
}
export default App;
Login file.
class SignInForm extends React.Component {
// constructor(props) {
// super(props);
state = {
temp: null,
};
// }
handleChange = (e) => {
e.preventDefault();
this.setState({
temp: e.target.value,
});
// this.props.addInput(e.target.value);
};
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.temp);
this.props.addInput(this.state.temp);
};
render() {
return (
<div className="container-form">
<form onSubmit={this.handleSubmit}>
<input
name="description"
type="text"
placeholder="add description"
onChange={this.handleChange}
value={this.state.input}
/>
<button type="submit">ADD</button>
</form>
</div>
);
}
}
export default SignInForm;
I'm not sure what is causing the problem, as I have another component that's almost identical except that the other component is stateless. I'm not sure if that makes a problem? It shouldn't right?
The following code gives me: Uncaught TypeError: this.props.dispatch is not a function at Signup.handleRegister, when trying to submit the form.
import React from 'react';
import { connect } from 'react-redux';
import { registerUser } from '../../actions/index';
export class Signup extends React.Component {
constructor(props){
super(props);
this.state = {
displayname: "",
username: "",
password: ""
}
}
handleRegister = e => {
e.preventDefault();
console.log('triggered handle register'); //logs: 'triggered handle register'
console.log(this.state); //logs: {displayname: "", username: "", password: ""}, as intended with empty inputs
console.log(this.props); //logs: {}
this.props.dispatch(registerUser(this.state));
}
render(){
return (
<div className="form-container sign-up-container">
<form className="sign-up-form" onSubmit={this.handleRegister}>
<h2>Create Account</h2>
<input type="text" placeholder="Display Name" onChange={e => this.setState({ displayname: e.target.value })} />
<input type="text" placeholder="Username" onChange={e => this.setState({ username: e.target.value })} />
<input type="password" placeholder="Password" onChange={e => this.setState({ password: e.target.value })} />
<button className="toggle-btn">Sign Up</button>
</form>
</div>
);
}
}
const mapStateToProps = state => ({});
export default connect(mapStateToProps)(Signup);
Update: Something like this?
const mapDispatchToProps = dispatch => {
return {
//the redux-action here instead of the handleRegister?
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Signup);
Update 2: Following Christopher Ngo suggestion
import React from 'react';
import { connect } from 'react-redux';
import { registerUser } from '../../actions/index';
export class Signup extends React.Component {
constructor(props) {
super(props);
this.state = {
displayname: "",
username: "",
password: ""
}
}
handleRegister = e => {
e.preventDefault();
console.log('triggered handle register'); //logs: 'triggered handle register'
console.log(this.state); //logs: {displayname: "", username: "", password: ""}, as intended with empty inputs
console.log(this);
//logs: Signup {props: {…}, context{…}, refs: {…}, updater: {…}, handleRegister: ƒ, …}
this.props.registerUser(this.state);
}
render() {
return (
<div className="form-container sign-up-container">
<form className="sign-up-form" onSubmit={this.handleRegister}>
<h2>Create Account</h2>
<input type="text" placeholder="Display Name" onChange={e => this.setState({ displayname: e.target.value })} />
<input type="text" placeholder="Username" onChange={e => this.setState({ username: e.target.value })} />
<input type="password" placeholder="Password" onChange={e => this.setState({ password: e.target.value })} />
<button className="toggle-btn">Sign Up</button>
</form>
</div>
);
}
}
// const mapStateToProps = state => ({});
const mapDispatchToProps = (dispatch) => {
return {
registerUser: (userInfo) => {
dispatch(registerUser(userInfo))
}
}
}
export default connect(null, mapDispatchToProps)(Signup);
I changed the console log in the handle register to check this and it looks like the Signup component still does not have props or dispatch available to it.
Your connected component is exported as a default export so you need to make sure that you are importing Signup as a default import in your other files and not a named export. In such scenarios its better to not export unconnected components to avoid such mistakes.
Import your signup component like
import Signup from 'path/to/Signup'
Try it like this:
import React from 'react';
import { connect } from 'react-redux';
import { registerUser } from '../../actions/index';
class Signup extends React.Component {
constructor(props){
super(props);
this.state = {
displayname: "",
username: "",
password: ""
}
}
handleRegister = e => {
e.preventDefault();
console.log('triggered handle register'); //logs: 'triggered handle register'
console.log(this.state); //logs: {displayname: "", username: "", password: ""}, as intended with empty inputs
console.log(this.props); //logs: {}
this.props.registerUser(this.state);
}
render(){
return (
<div className="form-container sign-up-container">
<form className="sign-up-form" onSubmit={this.handleRegister}>
<h2>Create Account</h2>
<input type="text" placeholder="Display Name" onChange={e => this.setState({ displayname: e.target.value })} />
<input type="text" placeholder="Username" onChange={e => this.setState({ username: e.target.value })} />
<input type="password" placeholder="Password" onChange={e => this.setState({ password: e.target.value })} />
<button className="toggle-btn">Sign Up</button>
</form>
</div>
);
}
}
const mapStateToProps = state => ({});
const mapDispatchToProps = (dispatch) => {
return{
registerUser: (userInfo) => {
dispatch(registerUser(userInfo))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Signup);
I have a simple form on child component A. On submit I'm passing the data from the form to the parent component and storing the data in state.. I want to then move this data to a different child, child component B.(the sibling of A)
I'm having trouble getting the data to be rendered on submit in component B. I'm not sure how to trigger the rendering on submit or how to pass this information via props on submit.
Here is the Parent
class Msg extends React.Component {
constructor(props) {
super(props);
this.storeInput = this.storeInput.bind(this);
this.state = {
name: '',
msg: ''
};
}
storeInput (d) {
this.setState({
name: d.name,
msg: d.msg
})
}
render() {
return(
<div className='msgContainer'>
<Input
passBack={this.storeInput}/>
<Output />
</div>
)
}
}
Here is Component A
class Input extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
name: '',
msg: ''
};
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
handleSubmit(e) {
e.preventDefault();
this.props.passBack(this.state);
}
render () {
const name = this.state.name;
const msg = this.state.msg;
return (
<div className='form-container'>
<form action="">
<label htmlFor="">name</label>
<input
name='name'
value={name}
onChange={this.handleChange}
type='text'></input>
<label htmlFor="">message</label>
<textarea
name='msg'
value={msg}
onChange={this.handleChange}
rows='5' cols='80'></textarea>
<input
onClick={this.handleSubmit}
type='submit'></input>
</form>
</div>
)
}
}
Here is Component B
class Output extends React.Component {
render () {
return(
<div className='output'>
</div>
)
}
}
Simply pass the state as props to Output like so:
Parent Component:
import React from 'react';
import Input from './Input';
import Output from './Output';
class Msg extends React.Component {
state = { name: '', msg: '' };
storeInput = d => {
this.setState({ name: d.name, msg: d.msg });
};
render() {
// destructure the state
const { name, msg } = this.state;
return (
<div className="msgContainer">
<Input passBack={this.storeInput} />
{/* pass the state as props to Output */}
<Output name={name} msg={msg} />
</div>
);
}
}
export default Msg;
Input.js
import React from 'react';
class Input extends React.Component {
state = { name: '', msg: '' };
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
this.props.passBack(this.state);
this.setState({ name: '', msg: '' }); // clear up the input after submit
};
render() {
const { name, msg } = this.state;
return (
<div className="form-container">
<form onSubmit={this.handleSubmit}>
<label htmlFor="">name</label>
<input
name="name"
value={name}
onChange={this.handleChange}
type="text"
/>
<label htmlFor="">message</label>
<textarea
name="msg"
value={msg}
onChange={this.handleChange}
rows="5"
cols="80"
/>
<input type="submit" />
</form>
</div>
);
}
}
export default Input;
Output.js
import React from 'react';
// destructure the props coming in from Msg
// no need for a class-based component
const Output = ({ name, msg }) => (
<div className="output">
<div>Output</div>
<p>{name}</p>
<p>{msg}</p>
</div>
);
export default Output;
Live demo: https://jsfiddle.net/c8th67zn/
This is my code. Am new for Reactjs, am trying to create form and display user info. I want to display the user details below the form after clicked the submit form
import React, {Component} from 'react';
class Input extends Component {
state = {
firstName: ''
}
displayNameHandler = (e) => {
let updatedName = e.target.value;
this.setState({firstName: updatedName});
//console.log(updatedName);
}
render() {
return(
<div>
<form>
<label>Enter the Name</label>
<input type="text" name="firstName" onChange={this.displayNameHandler}/>
<button type="button" onSubmit={e => this.displayNameHandler(e)}>Submit</button>
<p>"FirstName: " {this.state.firstName}</p>
</form>
</div>
);
}
}
export default Input;
Add onClick on button and change type its to submit. Use conditional rendering to show name on submit:
import React, { Component } from 'react';
class Input extends Component {
state = {
firstName: '',
showName: false
}
displayNameHandler = (e) => {
let updatedName = e.target.value;
this.setState({ firstName: updatedName });
//console.log(updatedName);
}
handleSubmit = (e) => {
e.preventDefault();
this.setState({
showName: true
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>Enter the Name</label>
<input type="text" name="firstName" onChange={this.displayNameHandler} value={this.state.firstName} />
<button type="submit" onClick={this.handleSubmit}>Submit</button>
{this.state.showName && <p>"FirstName: " {this.state.firstName}</p>}
</form>
</div>
);
}
}
export default Input;
if you want to use the button you should make another state to keep the submitted data and a state to keep changes in input field
import React, { Component } from "react";
class Input extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
submitedFirstName: ""
};
}
inputChange = e => {
const firstName = e.target.value;
this.setState(() => ({ firstName }));
};
displayNameHandler = () => {
this.setState(prevState => ({ submitedFirstName: prevState.firstName }));
};
render() {
return (
<div>
<form>
<label>Enter the Name</label>
<input type="text" name="firstName" onChange={this.inputChange} />
<button type="button" onClick={this.displayNameHandler}>
Submit
</button>
<p>
"FirstName: "
{this.state.submitedFirstName && this.state.submitedFirstName}
</p>
</form>
</div>
);
}
}
export default Input;
if you want to have on submit simply remove onClick from button cause it has a default type of submit and put an onSubmit in form component and also you sould prevent forms default behavior.
displayNameHandler = e => {
e.preventDefault();
this.setState(prevState => ({ submitedFirstName: prevState.firstName }));
};
and
<form onSubmit={this.displayNameHandler}>
<label>Enter the Name</label>
<input type="text" name="firstName" onChange={this.inputChange} />
<button>Submit</button>
<p>
"FirstName: " {this.state.submitedFirstName && this.state.submitedFirstName}
</p>
</form>
but you can also show data in input change
import React, { Component } from "react";
class Input extends Component {
constructor(props) {
super(props);
this.state = {
firstName: ""
};
}
inputChange = e => {
const firstName = e.target.value;
this.setState(() => ({ firstName }));
};
render() {
return (
<div>
<form>
<label>Enter the Name</label>
<input type="text" name="firstName" onChange={this.inputChange} />
<p>
"FirstName: "
{this.state.FirstName && this.state.FirstName}
</p>
</form>
</div>
);
}
}
export default Input;
also pay attention to the constructor.
Bellow form you should put something like this
{this.state.firstName !=="" && <p>{this.state.firstName}</p>}
import React, { Component } from 'react';
class Input extends Component {
state = {
firstName: '',
}
displayNameHandler = (e) => {
let updatedName = e.target.value;
this.setState({ firstName: updatedName });
//console.log(updatedName);
}
handleSubmit = () => {
alert("The Name you Entered is" , this.state.firstName);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>Enter the Name</label>
<input type="text" name="firstName" onChange={this.displayNameHandler} value={this.state.firstName} />
<button type="submit" onClick={this.handleSubmit}>Submit</button>
</form>
</div>
);
}
}
export default Input;