handleSubmit is not running React - Redux Form - handleSubmit - reactjs

Hi I'm making a gallery app using react-redux, react-redux-firebase.
Now, working on Login form and handleSubmit is not triggered. However, handleChange works just fine. Could someone help me?
import React from "react";
import { Link } from "react-router-dom";
export class SignIn extends React.Component {
constructor() {
super();
this.state = { email: "", password: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
console.log("onchange");
this.setState({ [e.target.id]: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
console.log("clicked");
this.props.signIn(this.state);
}
render() {
console.log(this.props);
return (
<div className="sign-in">
<ul className="active-or-not">
<li className="active-user">
<Link to="/Sign-in">Sign in</Link>
</li>
<li className="not-active-user">
<Link to="/Registration">New</Link>
</li>
</ul>
<div className="container">
<form className="form" onSubmit={this.handleSubmit}>
<div className="input-field">
<input
placeholder="Email"
className="input"
type="email"
id="email"
pattern="^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
onChange={this.handleChange}
/>
</div>
<div className="input-field">
<input
placeholder="Password"
type="password"
id="password"
pattern="^\S*$"
maxLength="20"
className="input"
onChange={this.handleChange}
/>
</div>
<div className="input-field">
<button type="submit" className="submit">
Go
</button>
</div>
</form>
</div>
</div>
);
}
}
Onchange triggered collectly and console shows result, but when clicked submit button nothing shows up.
I've been trying to see similar problem but can't find the actual idea how to fix it.

Related

How to accept and pass two parameter as props

Hi I need to pass two parameters, to the class Chat. Currently it is getting only one parameter and displaying correctly.
const Chat = props => (
<div >
<ul>{props.messages.map(message => <li key={message}>{message}</li>)}</ul>
</div>
);
This Chat.js file is called from the Home.js. Suppose I need to pass the Chat component two parameters and I tried it like following.
import React, { Component } from 'react';
import { User } from './User';
import Chat from './Chat';
export class Home extends Component {
displayName = Home.name
state = {
messages: [],
names: []
};
handleSubmit = (message,name) =>
this.setState(currentState => ({
messages: [...currentState.messages, message],
names: [...currentState.names,name]
}));
render() {
return (
<div>
<div>
<User onSubmit={this.handleSubmit} />
</div>
<div>
<Chat messages={this.state.messages,this.state.name} />
</div>
</div>
);
}
}
In this scenario how should I change the Chat component to accept two parameters and display inside div tags.
This is what I tried. But seems it is incorrect.
const Chat = props => (
<div >
<ul>{props.messages.map((message, name) => <li key={message}>{message}</li> <li key={name}>{name}</li>)}</ul>
</div>
);
PS: The User Method
import * as React from 'react';
export class User extends React.Component{
constructor(props) {
super(props);
this.state = {
name: '',
message: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div className="panel panel-default" id="frame1" onSubmit={this.handleSubmit}>
<form className="form-horizontal" action="/action_page.php" >
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="name">Your Name </label>
<div className="col-sm-10">
<input type="text" className="form-control" name="name" placeholder="Enter your Name" onChange={this.handleChange} />
</div>
</div>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="message">Message</label>
<div className="col-sm-10">
<input type="text" className="form-control" name="message" placeholder="Enter your Message" onChange={this.handleChange}/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit" id="submit" className="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
);
}
handleChange(evt) {
this.setState({ [evt.target.name]: evt.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
this.props.onSubmit(this.state.message, this.state.name);
this.setState({ message: "" });
this.setState({name:""});
};
}
You can do this by using separate attributes to pass different props. So for instance, you might revise your <Home/> components render method like so:
<Chat messages={this.state.messages} names={this.state.names} />
and then to access these two bits of data (messages and name) from inside the <Chat /> component you could do the following:
const Chat = props => (
<div >
<ul>{props.messages.map((message, index) => <li key={message}>
From: { Array.isArray(props.names) ? props.names[index] : '-' }
Message: {message}</li>)}
</ul>
</div>
);
Hope this helps!
You have to pass them separately:
<Chat messages={this.state.messages} name={this.state.name} />

React form with <Popup> alert message instead of alert()

I am trying to create a contact form in React. It sends the email. Everything is working fine. What I would like to achieve is to replace the alert('') with a better looking < Popup> message using react Popup package.
Here is the code:
import React, { Component } from 'react';
import '../css/Contact.css';
import axios from 'axios';
import Popup from "reactjs-popup";
class Contact extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
message: '',
isValid: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.validationCheck = this.validationCheck.bind(this);
}
handleChange = (event) => {
const name = event.target.id;
const value = event.target.value;
this.setState ({ [name] : value});
}
validationCheck () {
if((this.state.name.length)>3 &&
(this.state.message.length)>5 &&
(this.state.email.length)>7 &&
(this.state.email.includes("#")) &&
(this.state.email.includes(".")) &&
((this.state.name || this.state.message || this.state.message)!=0)
)
{
this.setState({ isValid: true});
this.forceUpdate();
};
}
async handleSubmit (event) {
this.validationCheck();
this.forceUpdate();
if ((this.state.isValid) === true) {
event.preventDefault();
const { name, email, message } = this.state;
const form = await axios.post('/api/form', {
name,
email,
message
});
alert('thank you for your message');
event.target.reset();
}
else {
event.preventDefault();
alert('you might have entered something wrong');
}
}
render() {
return (
<div className="contact">
<h1>Contact Me</h1>
<form id="form" onSubmit={this.handleSubmit}>
<div>
<label htmlFor="Name" className="badge badge-secondary">Name</label>
<input
onChange={this.handleChange} id="name" className="form-control" placeholder="Enter your name here."/>
</div>
<div>
<label htmlFor="Email" className="badge badge-secondary">Email address</label>
<input
onChange={this.handleChange}
id="email"
className="form-control"
placeholder="Enter your e-mail address here." />
</div>
<div className="">
<label htmlFor="Message" className="badge badge-secondary">Message</label>
<textarea
onChange={this.handleChange} rows="4"
className="form-control" id="message" placeholder="Enter your message here."></textarea>
</div>
<button
type="submit"
form="form"
className="btn btn-secondary btn-lg button"
id="submit"
value="Submit"> Send! </button>
</form>
<hr />
<button type="button" className="btn btn-outline-info" onClick={this.props.scrollToTop}>
Scroll me back to the top!</button>
</div>
);
}
}
export default Contact;
I have tried to replace 'alert('thank you for your message');' with return(< Popup>); but that is clearly not a way forward.
Here's a way how you can exactly use a reactjs-popup:
import React from "react";
import Popup from "reactjs-popup";
export default () => (
<Popup trigger={<button> Trigger</button>} position="right center">
<div>Popup content here !!</div>
</Popup>
);
All you need to do is put a trigger for it and it'll work
For help: https://react-popup.netlify.com/

unable to get enter and get value in REACT.js

I am new to ReactJS and trying to build a sample application
I am unable to get enter the value in textbox and unable to get the value in alert. Am I doing something wrong. I have tried the example given on React.Js Form, but not working.
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {value:''};
this.OnSubmit = this.OnSubmit.bind(this);
}
OnSubmit(event){
alert('name value is : '+this.state.value);
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text" value={this.state.value} />
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;
please change :
<input type="text" value={this.state.value} />
to:
<input type="text" value={this.state.value} onChange = {this.onChange}/>
In your class, add the 'onChange' function:
onChange(e){
this.setState({
value: e.target.value
})
}
and in your constructor:
this.onChange = this.onChange.bind(this)
Edit 1:
please check my codepen here
Edit 2:
If you have too many inputs, you can use a function like this:(it's just a rough example, in real world I'll create a new component to handle this together)
//in your constructor
this.state = {}
//in class 'controlled component way'
createInput(num){
let inputArray = []
for(let i = 0; i < num; i ++){
inputArray.push(<input key = {i} name = {i} onChange = {this.onChange} value = {this.state[i] || ''} />)
}
return inputArray
}
onChange(e){
let key = e.target.name
let newState = {}
newState[key] = e.target.value
this.setState(newState)
}
// in your render function
return <div>
{this.createInput(100)}
</div>
check my codepen here for this example
and of course you can also do this using uncontrolled component.
controlled component and uncontrolled
You can either bind onChange event to your input or setState when submiting the value , you cant change the state like that
Change your code to something like this
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {value:''};
this.OnSubmit = this.OnSubmit.bind(this);
}
OnSubmit(event){
this.setState({value: this.refs.infield.value},()=>{
alert('name value is : '+this.state.value);
})
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text" ref = "infield"/>
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;
Hi to get the value add a name to the input and an onChange function to set the value to the state and then do what evere you want in onsubmit function
I cant write you a working code now because I'm using my phone but my this Will help
onfieldchange(e) {
this.setState({[e.target.name]: e.target.value});
}
onaSubmit(){
//do your code here
}
....
....
<input type="text" name="firstName" value={this.state.firstName} />
Hope this help you
There are two ways to handle form elements in reactjs:
Controlled and uncontrolled components(using refs).In controlled component approach ,you have to add the state of the input field to the input field value and onChange event to it, which is the one you are trying to do.Here is the working code.
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {
firstname:''
};
this.OnSubmit = this.OnSubmit.bind(this);
this.OnChange = this.OnChange.bind(this);
}
OnSubmit(event){
alert('name value is : '+this.state.firstname);
event.preventDefault();
}
OnChange(){
this.setState({
[e.target.name] : [e.target.value]
});
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text"
name="firstname"
value={this.state.firstname}
OnChange={this.OnChange}
/>
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;

react bootstrap table not rendering data without refresh

i am using react-redux with react bootstrap table . my UI is given in picture . when i add payment the data is saved in database. i have used componentdidupdate and componentdidUpdate to render the props data . but nothing is working . the table does not render the data without refresh . please help......................................................................................................
import React from 'react';
import { connect } from 'react-redux';
// import {bindActionCreators} from 'redux'
import { Link } from 'react-router';
import Messages from '../Messages';
import classnames from 'classnames';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { getCrmOneCustomer, saveStatus, getCrmStatus } from '../../actions/crmAction';
//--------------------------------------------------------------------------
class CrmStatus extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '', shop_name: '', crm_id: '', status: ''
};
this.props.dispatch(getCrmOneCustomer(this.props.params.id));
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.props.dispatch(getCrmStatus(this.props.params.id));
}
//--------------------------------------------------------------------------
componentWillReceiveProps(newProps) {
console.log('componentWillReceiveProps............ from edit');
console.log(newProps)
this.setState({
name: newProps.CrmOne.name,
shop_name: newProps.CrmOne.shop_name,
status: newProps.CrmOne.status,
})
}
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleSubmit(event) {
event.preventDefault();
var Id = this.props.params.id;
var obj = {};
obj["crm_id"] = Id
obj["name"] = this.state.name
obj["shop_name"] = this.state.shop_name
obj["status"] = this.state.status
console.log(obj)
this.props.dispatch(saveStatus(obj))
}
//--------------------------------------------------------------------------
componentDidUpdate(){
this.products = this.props.CrmOneStatus
}
render() {
return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h2>CRM Status</h2>
</div>
</div>
<div className="row">
<div className="col-md-12">
<div className ="col-md-8">
<BootstrapTable data={this.products} striped hover pagination={true} search>
<TableHeaderColumn isKey dataField='name'>Name</TableHeaderColumn>
<TableHeaderColumn dataField='status'>status</TableHeaderColumn>
<TableHeaderColumn dataField='createdAt'>Date</TableHeaderColumn>
</BootstrapTable>
</div>
<div className ="col-md-4">
<h4> Add Payment </h4>
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<div className="form-group">
<label>
Name:
</label>
<input disabled type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Zahid Hasan" />
</div>
<div className="form-group">
<label>
shop name:
</label>
<input type="text" className="form-control" name="shop_name" value={this.state.shop_name} onChange={this.handleChange} placeholder="amount" />
</div>
<div className="form-group">
<label>
Status:
</label>
<textarea rows="8" cols="50" type="text" className="form-control" name="status" value={this.state.status} onChange={this.handleChange} placeholder="comment" />
</div>
<div className="btn-group" role="group">
<button type="submit" className="btn btn-success btn-lg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
// ======================== REDUX CONNECTORS ========================
const mapStateToProps = (state) => {
return {
CrmOne: state.crmCustomer.CrmOne,
CrmOneStatus: state.crmCustomer.CrmOneStatus
};
};
export default connect(mapStateToProps)(CrmStatus);
You are making a request to fetch the data in the componentDidMount function which is only executed once when the component has mounted, i.e the reason it works when you refresh the page, However you should get the data whenever the props change, i.e. use the componentWillReceiveProps function. Also you don't need to assign the props to the class variable, you can directly use the props to as data.
class CrmStatus extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '', shop_name: '', crm_id: '', status: ''
};
this.props.dispatch(getCrmOneCustomer(this.props.params.id));
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.props.dispatch(getCrmStatus(this.props.params.id));
}
componentWillReceiveProps(newProps) {
console.log('componentWillReceiveProps............ from edit');
console.log(newProps)
if(nextProps.params.id !== this.props.params.id) {
this.props.dispatch(getCrmStatus(nextProps.params.id));
}
this.setState({
name: newProps.CrmOne.name,
shop_name: newProps.CrmOne.shop_name,
status: newProps.CrmOne.status,
})
}
//--------------------------------------------------------------------------
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
//--------------------------------------------------------------------------
handleSubmit(event) {
event.preventDefault();
var Id = this.props.params.id;
var obj = {};
obj["crm_id"] = Id
obj["name"] = this.state.name
obj["shop_name"] = this.state.shop_name
obj["status"] = this.state.status
console.log(obj)
this.props.dispatch(saveStatus(obj))
}
//--------------------------------------------------------------------------
render() {
return (
<div className="container ca-container">
<div className="row">
<div className="col-md-12">
<h2>CRM Status</h2>
</div>
</div>
<div className="row">
<div className="col-md-12">
<div className ="col-md-8">
<BootstrapTable data={this.props.CrmOneStatus} striped hover pagination={true} search>
<TableHeaderColumn isKey dataField='name'>Name</TableHeaderColumn>
<TableHeaderColumn dataField='status'>status</TableHeaderColumn>
<TableHeaderColumn dataField='createdAt'>Date</TableHeaderColumn>
</BootstrapTable>
</div>
<div className ="col-md-4">
<h4> Add Payment </h4>
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<div className="form-group">
<label>
Name:
</label>
<input disabled type="text" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} placeholder="Zahid Hasan" />
</div>
<div className="form-group">
<label>
shop name:
</label>
<input type="text" className="form-control" name="shop_name" value={this.state.shop_name} onChange={this.handleChange} placeholder="amount" />
</div>
<div className="form-group">
<label>
Status:
</label>
<textarea rows="8" cols="50" type="text" className="form-control" name="status" value={this.state.status} onChange={this.handleChange} placeholder="comment" />
</div>
<div className="btn-group" role="group">
<button type="submit" className="btn btn-success btn-lg">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
in constructor i added this
this.props.dispatch(getCrmStatus(this.props.params.id));
and handle submit
this.props.dispatch(getCrmStatus(this.props.params.id));
and it works like charm !!!!!!!!!!!!!!

Cannot trigger component's function in my react app

I am currently working with react and I have runned into a problem this morning that i do not understand.
I am trying to handle a form submit from my component with a function by passing it in the onSubmit property but it does not trigger it. I then added a button to trigger a mock function with its onClick property, and i still got the same problem; it appears than I can't trigger my function and I cannot find any solution on the Google.
Here is my code so you can check it out:
import React from 'react';
import AgentsStore from '../stores/AgentsStore';
import AgentsActions from '../actions/AgentsActions';
class Agents extends React.Component {
constructor(props) {
super(props);
this.state = AgentsStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
AgentsStore.listen(this.onChange);
}
componentWillUnmount() {
AgentsStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
handleSubmit(event) {
event.preventDefault();
var user = {};
user.name = this.state.newUser.name.trim();
user.lastname = this.state.newUser.lastname.trim();
if (user.name && user.lastname) {
AgentsActions.createUser(user);
}
}
onClick() {
console.log('clicked');
}
render() {
return (
<div /*className='container'*/>
<div className='alert alert-info'>
Hello from Agents
</div>
<div className='panel panel-default'>
<div className='panel-heading'>Create User</div>
<div className='panel-body'>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className='form-group'>
<label className='control-label'>Name</label>
<input type='text'
className='form-control'
ref='nameTextField'
value={this.state.newUser.name}
onChange={AgentsActions.updateName} />
</div>
<div className='form-group'>
<label className='control-label'>Lastname</label>
<input type='text'
className='form-control'
ref='lastnameTextField'
value={this.state.newUser.lastname}
onChange={AgentsActions.updateLastname} />
</div>
<h4>Address</h4>
<button type='submit' className='btn btn-primary'>Submit</button>
</form>
<button onClick={this.onClick} className='btn btn-primary'>Submit</button>
</div>
</div>
</div>
)
}
}
export default Agents;
I do not know if I am missing something in my code or there is an error but i am kind of desperate. Also I am basing my code on another file that i have which is working just fine...
Thank you in advance for your time

Resources