Unable to Grab value from Textfield in React? - reactjs

Code is given below. where there is a form and I want to get value from textfield of FullName and Email but I am getting error of undefined property for email. I want to access the Text field value. How can I do that i this is not propare way. Note that I am not fluent in React.
Error I am Getting in my COde is Given below.
index.js?aa0c:21 Uncaught TypeError: Cannot read property 'email' of undefined
at Object.onClick (eval at ./app/containers/LoginPage/index.js (http://localhost:3001/0.chunk.js:7:1), <anonymous>:104:27)
at Object.proxiedMethod [as onClick] (eval at ./node_modules/react-proxy/modules/createPrototypeProxy.js (http://localhost:3001/main.js:2282:1), <anonymous>:44:30)
at EnhancedButton._this.handleClick (webpack:///./~/material-ui/internal/EnhancedButton.js?:144:21)
at Object.ReactErrorUtils.invokeGuardedCallback (webpack:///./~/react-dom/lib/ReactErrorUtils.js?:69:16)
at executeDispatch (webpack:///./~/react-dom/lib/EventPluginUtils.js?:85:21)
at Object.executeDispatchesInOrder (webpack:///./~/react-dom/lib/EventPluginUtils.js?:108:5)
at executeDispatchesAndRelease (webpack:///./~/react-dom/lib/EventPluginHub.js?:43:22)
at executeDispatchesAndReleaseTopLevel (webpack:///./~/react-dom/lib/EventPluginHub.js?:54:10)
at Array.forEach (native)
at forEachAccumulated (webpack:///./~/react-dom/lib/forEachAccumulated.js?:24:9)
at Object.processEventQueue (webpack:///./~/react-dom/lib/EventPluginHub.js?:257:7)
this is my index.js file.
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import TextField from 'material-ui/TextField';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import DatePicker from 'material-ui/DatePicker';
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import { GridList, GridTile } from 'material-ui/GridList';
import Checkbox from 'material-ui/Checkbox';
import RaisedButton from 'material-ui/RaisedButton';
export default class Login extends Component {
state = {
value: null,
};
onClick() {
const text = this.refs.email.getValue();
console.log("when clicking, the form data is:", text);
console.log(this.refs.email.getValue());
}
handleChange = (event, index, value) => this.setState({ value });
render() {
return (
<div className="md-card">
<div className="md-card-content large-padding">
<form id="form_validation" className="uk-form-stacked" >
<div className="uk-grid" data-uk-grid-margin>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<TextField
ref={(input) => { this.fullname = input; }}
floatingLabelText="Full Name"
fullWidth={true}
/>
</div>
</div>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<TextField
hintText=""
ref='email'
floatingLabelText="Email"
fullWidth={true}
/>
</div>
</div>
</div>
<div className="uk-grid" data-uk-grid-margin>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<DatePicker
hintText="Birthdate"
container="inline"
mode="landscape"
fullWidth={true}
/>
</div>
</div>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<label className="uk-form-label">Gender:</label>
<RadioButtonGroup name="shipSpeed" defaultSelected="not_light" >
<RadioButton
value="Male"
label="Male"
/>
<RadioButton
value="Female"
label="Female"
/>
</RadioButtonGroup>
</div>
</div>
</div>
<div className="uk-grid">
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<label className="uk-form-label">Hobbies:</label>
<span className="icheck-inline">
<Checkbox
label="Skiing"
/>
</span>
<span className="icheck-inline">
<Checkbox
label="Running"
/>
</span>
<span className="icheck-inline">
<Checkbox
label="Reading"
/>
</span>
<span className="icheck-inline">
<Checkbox
label="Swimming"
/>
</span>
</div>
</div>
<div className="uk-width-medium-1-2">
<SelectField
floatingLabelText="Press?"
value={this.state.value}
onChange={this.handleChange}
>
<MenuItem value={null} primaryText="" />
<MenuItem value={false} primaryText="Internet" />
<MenuItem value={true} primaryText="Words of Mouth" />
</SelectField>
</div>
</div>
<div>
<TextField
hintText=""
floatingLabelText="Message"
multiLine={true}
rows={2}
rowsMax={4}
fullWidth={true}
/>
</div>
<RaisedButton label="Primary" primary={true} onClick={this.onClick} />
</form >
</div>
</div>
);
}
}

Getting value of components (ex. Inputs) using ref is not right way in Reactive Functional Programming. (Read this: https://facebook.github.io/react/docs/forms.html)
Try to listen on change event of each Input and keep they changes into state, so you can provide a value to them and control them. This will able you to have values, clean them up or change them from somewhere else.
Here is your code with controlled inputs of fullname and email.
Also you can check this out in material-ui docs (under Controlled Example section of each component).
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import TextField from 'material-ui/TextField';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import DatePicker from 'material-ui/DatePicker';
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import { GridList, GridTile } from 'material-ui/GridList';
import Checkbox from 'material-ui/Checkbox';
import RaisedButton from 'material-ui/RaisedButton';
export default class Login extends Component {
state = {
value: null,
fullname: ""
email: ""
};
onClick() {
console.log(this.state.fullname);
console.log(this.state.email);
}
handleChange = (event, index, value) => this.setState({ value });
render() {
return (
<div className="md-card">
<div className="md-card-content large-padding">
<form id="form_validation" className="uk-form-stacked" >
<div className="uk-grid" data-uk-grid-margin>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<TextField
ref={(input) => { this.fullname = input; }}
floatingLabelText="Full Name"
fullWidth={true}
value={this.state.fullname}
onChange={(event, value) => { this.setState({ fullname: value }); }}
/>
</div>
</div>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<TextField
hintText=""
ref='email'
floatingLabelText="Email"
fullWidth={true}
value={this.state.email}
onChange={(event, value) => { this.setState({ email: value }); }}
/>
</div>
</div>
</div>
<div className="uk-grid" data-uk-grid-margin>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<DatePicker
hintText="Birthdate"
container="inline"
mode="landscape"
fullWidth={true}
/>
</div>
</div>
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<label className="uk-form-label">Gender:</label>
<RadioButtonGroup name="shipSpeed" defaultSelected="not_light" >
<RadioButton
value="Male"
label="Male"
/>
<RadioButton
value="Female"
label="Female"
/>
</RadioButtonGroup>
</div>
</div>
</div>
<div className="uk-grid">
<div className="uk-width-medium-1-2">
<div className="parsley-row">
<label className="uk-form-label">Hobbies:</label>
<span className="icheck-inline">
<Checkbox
label="Skiing"
/>
</span>
<span className="icheck-inline">
<Checkbox
label="Running"
/>
</span>
<span className="icheck-inline">
<Checkbox
label="Reading"
/>
</span>
<span className="icheck-inline">
<Checkbox
label="Swimming"
/>
</span>
</div>
</div>
<div className="uk-width-medium-1-2">
<SelectField
floatingLabelText="Press?"
value={this.state.value}
onChange={this.handleChange}
>
<MenuItem value={null} primaryText="" />
<MenuItem value={false} primaryText="Internet" />
<MenuItem value={true} primaryText="Words of Mouth" />
</SelectField>
</div>
</div>
<div>
<TextField
hintText=""
floatingLabelText="Message"
multiLine={true}
rows={2}
rowsMax={4}
fullWidth={true}
/>
</div>
<RaisedButton label="Primary" primary={true} onClick={this.onClick} />
</form >
</div>
</div>
);
}
}

Related

How to Redirect a Register Page to another Page using React & Formik

The page is not responding after clicking the sign up button, I wonder what went wrong with the code. I want it to redirect to "dashboards/elearning" page. The NavLink points not to the Sign Up button, and if I add a NavLink around sign up button, the validation would be pointless.
Below is the register.js file.
import React from 'react';
import { NavLink } from 'react-router-dom';
import { Button, Form } from 'react-bootstrap';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import LayoutFullpage from 'layout/LayoutFullpage';
import CsLineIcons from 'cs-line-icons/CsLineIcons';
import HtmlHead from 'components/html-head/HtmlHead';
const Register = () => {
const title = 'Register';
const description = 'Register Page';
const validationSchema = Yup.object().shape({
name: Yup.string().required('Name is required'),
email: Yup.string().email().required('Email is required'),
password: Yup.string().min(6, 'Must be at least 6 chars!').required('Password is required'),
terms: Yup.bool().required().oneOf([true], 'Terms must be accepted'),
});
const initialValues = { name: '', email: '', password: '', terms: false };
const onSubmit = (values) => console.log('submit form', values);
const formik = useFormik({ initialValues, validationSchema, onSubmit });
const { handleSubmit, handleChange, values, touched, errors } = formik;
const leftSide = (
<div className="min-h-100 d-flex align-items-center">
<div className="w-100 w-lg-75 w-xxl-50">
<div>
<div className="mb-5">
<h1 className="display-3 text-white">Multiple Niches</h1>
<h1 className="display-3 text-white">Ready for Your Project</h1>
</div>
<p className="h6 text-white lh-1-5 mb-5">
Dynamically target high-payoff intellectual capital for customized technologies. Objectively integrate emerging core competencies before
process-centric communities...
</p>
<div className="mb-5">
<Button size="lg" variant="outline-white" href="/">
Learn More
</Button>
</div>
</div>
</div>
</div>
);
// if <NavLink to="/dashboards/elearning"> Sign up </NavLink>, all other validation mathods invalid
const rightSide = (
<div className="sw-lg-70 min-h-100 bg-foreground d-flex justify-content-center align-items-center shadow-deep py-5 full-page-content-right-border">
<div className="sw-lg-50 px-5">
<div className="sh-11">
<NavLink to="/dashboards/elearning">
<div className="logo-default" />
</NavLink>
</div>
<div className="mb-5">
<h2 className="cta-1 mb-0 text-primary">Welcome,</h2>
<h2 className="cta-1 text-primary">let's get the ball rolling!</h2>
</div>
<div className="mb-5">
<p className="h6">Please use the form to register.</p>
<p className="h6">
If you are a member, please <NavLink to="/login">login</NavLink>.
</p>
</div>
<div>
<form id="registerForm" className="tooltip-end-bottom" onSubmit={handleSubmit}>
<div className="mb-3 filled form-group tooltip-end-top">
<CsLineIcons icon="user" />
<Form.Control type="text" name="name" placeholder="Name" value={values.name} onChange={handleChange} />
{errors.name && touched.name && <div className="d-block invalid-tooltip">{errors.name}</div>}
</div>
<div className="mb-3 filled form-group tooltip-end-top">
<CsLineIcons icon="email" />
<Form.Control type="text" name="email" placeholder="Email" value={values.email} onChange={handleChange} />
{errors.email && touched.email && <div className="d-block invalid-tooltip">{errors.email}</div>}
</div>
<div className="mb-3 filled form-group tooltip-end-top">
<CsLineIcons icon="lock-off" />
<Form.Control type="password" name="password" onChange={handleChange} value={values.password} placeholder="Password" />
{errors.password && touched.password && <div className="d-block invalid-tooltip">{errors.password}</div>}
</div>
<div className="mb-3 position-relative form-group">
<div className="form-check">
<input type="checkbox" className="form-check-input" name="terms" onChange={handleChange} value={values.terms} />
<label className="form-check-label">
I have read and accept the{' '}
<NavLink to="/dashboards/elearning" target="_blank">
terms and conditions.
</NavLink>
</label>
{errors.terms && touched.terms && <div className="d-block invalid-tooltip">{errors.terms}</div>}
</div>
</div>
<Button size="lg" type="submit">
Signup
</Button>
</form>
</div>
</div>
</div>
);
return (
<>
<HtmlHead title={title} description={description} />
<LayoutFullpage left={leftSide} right={rightSide} />
</>
);
};
export default Register;
You can use the useNavigate hook from react-router-dom
Please find the necessary snippet below.
import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
const onSubmit = (values) => {
console.log('submit form', values);
navigate('dashboards/elearning');
};
...

What is the flow of control?

I am not understanding the flow of control since I am a newbie. In this code, after the component is rendered, useEffects get called. When the first useEffect is called, it is dispatching an action. So, after the action is dispatched, it should re-render the component because I am fetching the change in state from useSelector. Instead, it is executing the second useEffect. Similar is the case with the third useEffect, after it is triggered, it is changing the formData which is in useState. Instead of re-rendering, it is executing the 4th useEffect. Can anyone please help me understand the flow right from the start to the end?
import React,{useState,useEffect,useRef} from "react";
import AdminLayout from "../../../hoc/adminLayout";
import {useFormik,FieldArray,FormikProvider} from "formik";
import {useDispatch,useSelector} from "react-redux";
import {validation,formValues} from "./validationSchema";
import {getAdminArticle,updateArticle} from "../../../store/actions/articles_actions";
import {clearCurrentArticle} from "../../../store/actions/index";
import Loader from "../../../utils/loader";
import {
TextField,
Button,
Divider,
Chip,
Paper,
InputBase,
IconButton,
Select,
MenuItem,
FormControl,
FormHelperText
} from '#material-ui/core';
import AddIcon from '#material-ui/icons/Add';
import WYSIWYG from "../../../utils/forms/wysiwyg";
const EditArticle=(props)=>{
const dispatch=useDispatch();
const notifications=useSelector((state)=>{
return state.notifications;
})
const articles=useSelector((state)=>{
return state.articles;
})
const [isLoading, setIsLoading]=useState(true);
const [editorBlur,setEditorBlur]=useState(false);
const [formData,setFormData]=useState(formValues);
const actorsValue=useRef("");
/////edit/////
const [editContent,setEditContent]=useState(null);
////edit////
const formik=useFormik({
enableReinitialize:true,
initialValues:formData,
validationSchema:validation,
onSubmit:(values,{resetForm})=>{
//console.log(values);
setIsLoading(true);
dispatch(updateArticle(values,props.match.params.id));
}
});
const handleEditorState=(state)=>{
formik.setFieldValue("content",state,true);
}
const handleEditorBlur=(blur)=>{
setEditorBlur(true);
}
const errorHelper=(formik,value)=>{
return {
error:formik.errors[value] && formik.touched[value]? true:false,
helperText:formik.errors[value] && formik.touched[value]?formik.errors[value]:null
}
}
///////edit/////////
useEffect(()=>{
console.log("first");
dispatch(getAdminArticle(props.match.params.id));
},[dispatch,props.match.params])
/////edit///////
useEffect(()=>{
console.log("second");
// if(notifications && notifications.success){
// props.history.push("/dashboard/articles");
// }
// if(notifications && notifications.error){
setIsLoading(false);
// }
},[notifications,props.history])
useEffect(()=>{
console.log("third");
if(articles && articles.current){
setFormData(articles.current);
setEditContent(articles.current.content);
}
},[articles])
useEffect(()=>{
console.log("unmounted");
return ()=>{
dispatch(clearCurrentArticle());
}
},[dispatch])
return <AdminLayout section="Add Article">
{console.log("rendered")}
{isLoading?<Loader />:<form className="mt-3 article_form" onSubmit={formik.handleSubmit}>
<div className="form-group">
<TextField
style={{width:"100%"}}
name="title"
label="Enter a title"
variant="outlined"
{...formik.getFieldProps("title")}
{...errorHelper(formik,"title")}
/>
</div>
<div className="form-group">
<WYSIWYG setEditorState={(state)=>{
return handleEditorState(state)
}} setEditorBlur={(blur)=>{
return handleEditorBlur(blur)
}}
editContent={editContent}
/>
{formik.errors.content && editorBlur?
<FormHelperText error={true}>
{formik.errors.content}
</FormHelperText> :null}
<TextField
type="hidden"
name="content"
{...formik.getFieldProps("content")}
/>
</div>
<div className="form-group">
<TextField
style={{width:"100%"}}
name="excerpt"
label="Enter an excerpt"
variant="outlined"
{...formik.getFieldProps("excerpt")}
{...errorHelper(formik,"excerpt")}
multiline
rows={4}
/>
</div>
<Divider className="mt-3 mb-3" />
<h5>Movie Data and Score</h5>
<div className="form-group">
<TextField
style={{width:"100%"}}
name="score"
label="Enter an score"
variant="outlined"
{...formik.getFieldProps("score")}
{...errorHelper(formik,"score")}
/>
</div>
<FormikProvider value={formik}>
<h5>Add the Actors</h5>
<FieldArray name="actors"
render={
arrayhelpers=>(
<div>
<Paper className="actors_form">
<InputBase
className="input"
placeholder="Add actor name here"
inputRef={actorsValue}
/>
<IconButton onClick={()=>{
arrayhelpers.push(actorsValue.current.value);
actorsValue.current.value="";
}}>
<AddIcon />
</IconButton>
</Paper>
{formik.errors.actors && formik.touched.actors?
<FormHelperText error={true}>
{formik.errors.actors}
</FormHelperText> :null}
<div className="chip_container">
{formik.values.actors.map((actor,index)=>{
return <div key={actor}>
<Chip label={`${actor}`} color="primary" onDelete={()=>{
return arrayhelpers.remove(index);
}}>
</Chip>
</div>
})}
</div>
</div>
)
}
/>
</FormikProvider>
<div className="form-group">
<TextField
style={{width:"100%"}}
name="score"
label="Enter the Director"
variant="outlined"
{...formik.getFieldProps("director")}
{...errorHelper(formik,"director")}
/>
</div>
<FormControl variant="outlined" >
<h5>Select a Status</h5>
<Select
name="status"
{...formik.getFieldProps("status")}
error={formik.errors.status && formik.touched.status? true:false}
>
<MenuItem value=""><em>None</em></MenuItem>
<MenuItem value="draft">Draft</MenuItem>
<MenuItem value="public">Public</MenuItem>
</Select>
{formik.errors.status && formik.touched.status?
<FormHelperText error={true}>
{formik.errors.status}
</FormHelperText> :null}
</FormControl>
<Divider className="mt-3 mb-3" />
<Button variant="contained" color="primary" type="submit" >
Edit Article
</Button>
</form>
}
</AdminLayout>
}
export default EditArticle;
[enter image description here][1]

React : TypeError: this.props.users.map is not a function

When I am adding a user and on submitting the user details it is redirecting back to the '/' route(which should display the users with their details) with an error. I've tried checking if the user is present then only do the mapping but it is not working. Can someone please help me to solve this, so that when I redirect back it should display the user that is added. The '/' route displays the List Users Page.
Here's the code:
UserForm.js
import React, { Component } from 'react'
import { Field, reduxForm } from 'redux-form'
import { connect } from 'react-redux'
import axios from 'axios'
import Checkbox from './Checkbox'
class UserForm extends Component {
renderInput(formProps) {
const className = `field ${formProps.meta.error && formProps.meta.touched ?
'error' : ''}`
return (
<div className={className}>
<label>{formProps.label}</label>
<input {...formProps.input} type={formProps.type} max={formProps.max} autoComplete='off'
label={formProps.label} id={formProps.id}
checked={formProps.input.value} />
{formProps.meta.touched &&
(formProps.meta.error && <span>{formProps.meta.error}</span>)}
</div>
)
}
onSubmit = (formValues) => {
console.log('formValues', formValues)
this.props.onSubmit(formValues)
}
render() {
const { handleSubmit } = this.props
const current = new Date().toISOString().split("T")[0]
let optionsList = [{ id: 1, name: 'Travelling' }, { id: 2, name: 'Reading' }, { id: 3, name: 'Gaming' }]
const colleges=['Pune University','S.P.College','F.C College']
return (
<div className='container'>
<form onSubmit={handleSubmit(this.onSubmit)}
className='ui form error'>
<div className='row mb-3'>
<label className='col-sm-2 col-form-label'>FullName</label>
<div className='col-sm-10'>
<Field name='fullname' component={this.renderInput}
type='text' className='form-control' />
</div>
</div>
<div className='row mb-3'>
<label className='col-sm-2 col-form-label'>Address</label>
<div className='col-sm-10'>
<Field name='address' component={this.renderInput}
type='text' />
</div>
</div>
<div className='row mb-3'>
<label className='col-sm-2 col-form-label'>BirthDate</label>
<div className='col-sm-10'>
<Field name='birthdate' component={this.renderInput}
type='date'
max={current} />
</div>
</div>
<div className='row mb-3'>
<label className='col-sm-2 col-form-label'>Select Your Gender</label>
<div className='col-sm-10 ui radio'>
<div className='form-check'>
<label className='form-check-label'>Male</label>
<Field name='gender' component='input' type='radio' value='male'
className='ui input' />{' '}
</div>
<div className='form-check'>
<label className='form-check-label'>Female</label>
<Field name='gender' component='input' type='radio' value='female'
/>{' '}
</div>
<div className='form-check'>
<label className='form-check-label'>Other</label>
<Field name='gender' component='input' type='radio' value='other'
/>{' '}
</div>
</div>
</div>
<div className='row mb-3'>
<label className='col-sm-2 '>Select Your Hobbies</label>
<div className='col-sm-10 ui checkbox'>
<Field name='roles' component={Checkbox} options={optionsList} type='checkbox' />
</div>
</div>
<div className='row mb-3'>
<label className='col-sm-2 col-form-label'>Select College</label>
<div className='col-sm-10'>
<Field name='college' component='select'>
<option value="">Select a college</option>
{colleges.map(collegeOption => (
<option value={collegeOption} key={collegeOption}>
{collegeOption}
</option>
))}
</Field>
</div>
</div>
<button type='submit' className='ui button'>Submit</button>
</form>
</div>
)
}
}
const validate = (formValues) => {
const errors = {}
if (!formValues.fullname) {
errors.fullname = 'You must enter a fullname'
}
if (!formValues.address) {
errors.address = 'You must enter the address'
}
if (!formValues.birthdate) {
errors.birthdate = 'Please select your date of birth'
}
if (!formValues.gender) {
errors.gender = 'Please select your gender'
}
if(!formValues.college){
errors.college='Please select your college'
}
return errors
}
export default reduxForm({
form: 'userform',
validate: validate
})(UserForm)
AddUser.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addUser } from '../../actions'
import UserForm from './UserForm'
class AddUser extends Component {
onSubmit = (formValues) => {
console.log('formValues', formValues)
this.props.addUser(formValues)
}
render() {
return(
<>
<div>Add User</div>
<UserForm onSubmit={this.onSubmit}/>
</>
)
}
}
export default connect(null, {
addUser: addUser
})(AddUser)
ListUsers.js
import React, { Component } from 'react'
import {connect} from 'react-redux'
import {listAllUsers} from '../../actions'
import {Link} from 'react-router-dom'
class ListUsers extends Component {
componentDidMount(){
this.props.listAllUsers()
}
usersList(){
return this.props.users && this.props.users.map((user)=>{
return (
<div key={user.id}>
<div>{user.fullname}</div>
<div>{user.address}</div>
<div>{user.birthdate}</div>
<div>{user.gender}</div>
<div>{user.hobbies}</div>
<div>{user.college}</div>
<div>{user.roles}</div>
<div>
<Link to={`/users/edituser/${user.id}`} className='ui button secondary'>Edit</Link>
</div>
<div>
<Link to={`/users/deleteuser/${user.id}`} className='ui button negative'>Delete</Link>
</div>
</div>
)
})
}
render() {
return (
<div>
<Link to='/users/adduser' >Add User</Link>
<h1>Users List</h1>
{this.usersList()}
</div>
)
}
}
const mapStateToProps=(state)=>{
console.log(state)
return {users:state.users}
}
export default connect(mapStateToProps,{listAllUsers:listAllUsers})(ListUsers)
The map() function is available on arrays and it looks like users is not one. Check the type of users and ensure that it's an array.

How to pass data from one component to another in React or React-Redux?

import React, { Component } from 'react';
class BigText extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
text: '',
summary: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<div>
<div>
<div className="row animated fadeIn">
<div className="px-1" style={{ width:100 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Text"
name="text"
value={this.state.text}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Summary"
name="summary"
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
</div>
<div>
</div>
</div>
</div>
</div>
)
}
}
export default BigText;
import React, { Component } from 'react';
import BigText from './bigText.js';
import InboxStyle from './inboxStyle.js';
import ImageStyle from './imageStyle.js';
import BigTextMobile from './bigText.mobile.js';
import InboxStyleMobile from './inboxStyle.mobile.js';
import ImageStyleMobile from './imageStyle.mobile.js';
class BasicNotification extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleClick = this.handleClick.bind(this);
}
static contextTypes = {
router: React.PropTypes.object
}
handleClick() {
this.context.router.push('/notifications');
}
handleChange(event) {
this.setState({value: event.target.value});
}
checkRadio =(e) =>{
if(e.target.checked) {
this.setState({layout: e.target.value});
}
}
render() {
return (
<div>
<div>
<h1 className="px-2">Create Notification</h1>
<hr />
<div className="row px-1 py-2 animated fadeIn">
<div className="px-1 mr-2" style={{ width:50 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Text"
name="text"
/>
</div>
<div>
<select placeholder="Logo" className="form-control" onChange={this.handleChange}>
<option default>Select Logo</option>
<option>Default</option>
<option>Custom</option>
</select>
</div>
<div><br />
<div className="btn-group" data-toggle="buttons">
<label className="btn btn-css btn-outline-secondary">
<input type="radio" name="layout" value="image" onChange={this.checkRadio}/>ImageStyle
</label>
<label className="btn btn-css btn-outline-secondary">
<input type="radio" name="layout" value="big" onChange={this.checkRadio}/>BigText
</label>
<label className="btn btn-css btn-outline-secondary">
<input type="radio" name="layout" value="inbox" onChange={this.checkRadio}/>InboxStyle
</label>
</div>
{
(this.state.layout === "big")?
<BigText/>:
(this.state.layout === "image")?
<ImageStyle/>:
(this.state.layout === "inbox")?
<InboxStyle/>:
null
}
<br />
<div className="row px-1" >
<div>
<button className="nav-link btn btn-block btn-info" onClick={this.handleClick} >Save</button>
</div>
<div className="px-1">
<button className="nav-link btn btn-block btn-danger"> Cancel</button>
</div>
</div>
</div><br />
</div>
<div>
{
(this.state.layout === "big")?
<BigTextMobile text={this.state.text} summary={this.state.summary} title={this.state.title}/>:
(this.state.layout === "image")?
<ImageStyleMobile/>:
(this.state.layout === "inbox")?
<InboxStyleMobile/>:
null
}
</div>
</div>
</div>
</div>
)
}
}
export default BasicNotification;
This is the screen i made on which I had imported three files which will be shown on clicking radio buttons.
Also there is a relevant mobile screen as well shown aside
now for example i imported as you can see BigText , it is containing the form
Now i want to print its input values in BigTextMobile Component
To simplify the solution you can do something like this:
<BigText onChange={data => {this.setState({ data })}} />
In the BigText component then you can put some data via this callback like this:
handleInputChange(event) {
const data = {
[event.target.name]: event.target.value
};
this.setState(data );
this.props.onChange(data);
}
And transfer this data to your BigTextMobile component from state:
<BigTextMobile data={this.state.data} ... />

Clicking Next button doesn't taking it to next page

import React from 'react';
import { Link } from 'react-router';
import { Field } from 'redux-form';
import BaseForm from '..//BaseForm';
export default class XXXXXXX extends BaseForm {
componentWillMount() {
this.props.retrieveAcademies();
}
render() {
const {
handleSubmit,
formatGraduationDate,
pristine,
submitting,
infoError,
acadamyId
} = this.props;
return (
<div className="col-md-8 col-lg-8 mscs-text">
<div>
<h1 className="mscs-head">Self Registration </h1> <hr />
<form onSubmit={handleSubmit(this.props.startRegistrationProcess.bind(this))} className="registration-step1Class">
<div className="form-section">
<label htmlFor="firstName">First Name:</label>
<Field name="firstName" component={this.renderInputield} label="Enter first Name:" />
</div>
<div className="form-section">
<label htmlFor="lastName">Last Name:</label>
<Field name="lastName" component={this.renderInputield} label="Enter last Name:" />
</div>
<div id="datetimepicker2" className="form-section">
<label htmlFor="dob">Date of Birth:</label>
<Field name="dob" component={this.renderReactDatePicker} type="text" />
</div>
<div className="form-section">
<label htmlFor="maritimeAcadamy">Maritime Academy:</label>
{this.renderAcademiesSelection(acadamyId)}
</div>
<div className="form-section">
<label htmlFor="Yearpassed">Year Passed:</label>
<Field name="passedYear"
component={this.renderReactDatePicker}
type="text"
formatDate={formatGraduationDate}
/>
</div>
<br />
<div className="form-section">
<label htmlFor="CustomerNumber">Customer ID:</label>
<Field name="CustomerNumber" component={this.renderInputield} type="text" label="Enter Customer ID:" />
</div>
<div className="error validation-error">
{infoError && infoError.error} <br />
</div>
<input type="submit" className="btn btn-success" value="Next" />
<input type="reset" className="btn btn-default" value="Cancel" />
</form>
</div>
</div>
);
}
renderAcademiesSelection(acadamyId) {
return (
<div>
<select className="form-control" {...acadamyId}>
<option key={0} value={''}>{'Select your academy'}</option>
{
this.props.academies && this.props.academies.map(function (item, index) {
return (
<option key={item.Id} value={item.Id}>{item.Name}</option>
);
})
}
</select>
</div>
);
}
}
This is the component. Below is the container. The code has some textboxes and dropdowns and calendar controls.
Container :
function mapStateToProps(state, ownProps) {
return {
academies: state.academies.academies,
infoError: state.signUp.error
};
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
retrieveAcademies: () => {
dispatch(retrieveAcademies());
},
startRegistrationProcess: dispatchGenerateRegistrationToken.bind(this),
nextPage: ownProps.nextPage,
}
}
The above code samples are my react component and container. When I am clicking on the Next button it is not taking me to the next step and it is not showing any type of error in the console. I don't know where exactly the mistake is. I can't debug since the console is not giving any type of error. Any help is appreciated here.

Resources