I have 3 components: App, CV and EXP_FORM.
APP have state where i store data from EXP_FORM and after that i render it by CV component. Issue is when i type in input fields in EXP_FORM CV updates it in one step behind.
for example: if i type in position input field in EXP_FORM "soft" in CV i will got "sof"
app.js
import React,{Component} from "react";
import CV from "./components/CV"
import EXP_FORM from "./components/Exp_form";
class App extends Component {
constructor(){
super()
this.state = {
name: '',
email: '',
phone: '',
//educationLs:[],
experienceLs:[{id:0}],
}
this.handleChange = this.handleChange.bind(this)
this.handleExp = this.handleExp.bind(this)
}
form_style = {
display: 'grid'
}
handleChange(event){
this.setState({
[event.target.id] : event.target.value
})
}
handleExp = (exp) => {
this.setState({
experienceLs: this.state.experienceLs.map(u => u.id !== exp.id ? u : exp),
})
}
render(){
const {name, email, phone, educationLs,experienceLs} = this.state
return (
<div>
<form style={this.form_style}>
<label htmlFor='nameInput'>Name: </label>
<input type='text' id='name' onChange={this.handleChange}/>
<label htmlFor='emailInput'>Email: </label>
<input type='text' id='email' onChange={this.handleChange}/>
<label htmlFor='phoneInput'>Phone: </label>
<input type='text' id='phone' onChange={this.handleChange}/>
</form>
<EXP_FORM id={0} callback={this.handleExp}/>
<div>
<CV name={name} email={email} phone={phone} exp={experienceLs} />
</div>
</div>
)
}
}
export default App;
EXP_FORM.js
import React from 'react'
class EXP_FORM extends React.Component {
constructor(props){
super(props)
this.state = {
id: props.id,
position: '',
company: '',
city:'',
from: '',
to: ''
}
this.handleChange = this.handleChange.bind(this)
}
form_style = {
display:'grid'
}
handleChange(event){
this.setState({
[event.target.name] : event.target.value
})
}
onTrigger = () => {
this.props.callback(this.state)
}
onChangeEvents = (event) => {
this.handleChange(event)
this.onTrigger()
}
render(){
const {position} = this.state
return(
<div>
<form style={this.form_style} onChange={this.onChangeEvents}>
<label htmlFor='position'>Position: {position}</label>
<input type='text' name='position'/>
<label htmlFor='company'>Company: </label>
<input type='text' name='company'/>
<label htmlFor='city'>City: </label>
<input type='text' name='city'/>
<label htmlFor='from'>From: </label>
<input type='text' name='from'/>
<label htmlFor='to'>To: </label>
<input type='text' name='to'/>
</form>
</div>
)
}
}
export default EXP_FORM
CV.js
import React from "react"
const CV = (props)=>{
const exp = props.exp.map((e) =>
<div key={e.id}>
<p>position: {e.position}</p>
<p>in {e.company}</p>
<p>From {e.from} until {e.to}</p>
<p>city:{e.city}</p>
</div>);
return(
<div>
<h1>Name: <span>{props.name}</span></h1>
<h1>Email: <span>{props.email}</span></h1>
<h1>Phone: <span>{props.phone}</span></h1>
<h1>Experience:</h1>
{exp}
</div>
)
}
export default CV
whats wrong ?
Related
I have blockchain application and created Reactjs interface to send data from user to application but when i enter data and try send it get error as follow , any one can help me?
The error is :
XHR POST http://localhost:3000/api/MedicalRecord
[HTTP/1.1 422 Unprocessable Entity 19ms]
The App.js file as follow
import React, { Component } from 'react';
import PostForm from './PostForm'
function App() {
return (
<div className="App">
<PostForm></PostForm>
</div>
);
}
export default App;
The PostForm.js file as follow
import React, { Component } from 'react'
import axios from 'axios'
class PostRecords extends Component {
constructor(props){
super(props)
this.state = {
record_Id: "",
patient: "",
doctor: "",
description: "",
prescription: ""
}
}
handleChange =(e) =>{
this.setState({
[e.target.name]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
axios.post('http://localhost:3000/api/MedicalRecord')
.then(response =>{
console.log(response)
})
}
render() {
const {record_id, patient, doctor, description, prescription} = this.state
return (
<div>
<form onSubmit={this.handleSubmit}>
<div>
<label>record_id :</label>
<input
type='text'
name ='record_id'
value={record_id}
onChange={this.handleChange}
></input>
</div>
<div>
<label>patient :</label>
<input
type='text'
name ='patient'
value={patient}
onChange={this.handleChange}
></input>
</div>
<div>
<label>doctor :</label>
<input
type='text'
name ='doctor'
value={doctor}
onChange={this.handleChange}
></input>
</div>
<div>
<label>description :</label>
<input
type='text'
name ='description'
value={description}
onChange={this.handleChange}
></input>
</div>
<div>
<label>prescription :</label>
<input
type='text'
name ='prescription'
value={prescription}
onChange={this.handleChange}
></input>
</div>
<button type='submit'>Submit Now</button>
</form>
</div>
)
}
}
export default PostRecords
I have a long list of checkboxes (not that optimised) and I want to get them in a state(the checked one) and I'm not really sure how to handle it hope for help(should also handle uncheck when clicked)...
<div className=' row float-center d-flex justify-content-center '>
<label className='m-3'>
<input
name='1'
type='checkbox'
checked={this.state.isGoing}
onChange={this.handleInputChange}
/>
1
</label>
<label className=' m-3'>
<input
name='1.5'
type='checkbox'
checked={this.state.isGoing}
onChange={this.handleInputChange}
/>
1.5
</label>
</div>
class Human extends React.Component {
constructor(props) {
super(props);
this.state = {
checkState: {
isGoing1: false,
isGoing2: false
}
};
}
handleInputChange = (event) => {
this.setState({
...this.state,
checkState: {
...this.state.checkState,
[event.target.name]: event.target.checked
}
});
};
render() {
return (
<div className=" row float-center d-flex justify-content-center ">
<label className="m-3">
<input
name="isGoing1"
type="checkbox"
checked={this.state.isGoing1}
onChange={this.handleInputChange}
/>
1
</label>
<label className=" m-3">
<input
name="isGoing2"
type="checkbox"
checked={this.state.isGoing2}
onChange={this.handleInputChange}
/>
1.5
</label>
</div>
);
}
}
This is it:
import React, { Component, Fragment } from "react";
import "./style.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { isGoing1: false, isGoing2: false };
this.handleInputChange1 = this.handleInputChange1.bind(this);
this.handleInputChange2 = this.handleInputChange2.bind(this);
}
componentDidMount() {
this.setState({ isGoing1: false });
this.setState({ isGoing2: false });
}
componentWillUnmount() {
this.setState({ isGoing1: false });
this.setState({ isGoing2: false });
}
componentDidUpdate(prevProps) {
console.log("isGoing1" + this.state.isGoing1);
console.log("isGoing2" + this.state.isGoing2);
}
handleInputChange1 = () => {
this.setState(state => ({
isGoing1: !state.isGoing1
}));
};
handleInputChange2 = () => {
this.setState(state => ({
isGoing2: !state.isGoing2
}));
};
render() {
return (
<div className=" row float-center d-flex justify-content-center ">
<label className="m-3">
<input
name="1"
type="checkbox"
checked={this.state.isGoing1}
onChange={this.handleInputChange1}
/>
1
</label>
<label className=" m-3">
<input
name="1.5"
type="checkbox"
checked={this.state.isGoing2}
onChange={this.handleInputChange2}
/>
1.5
</label>
</div>
);
}
}
see: https://stackblitz.com/edit/react-dw9ff6
I am following along with this tutorial (https://medium.com/#beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1) and am trying to print to console through the onSubmit function but this is not occurring and I do not know why. I've made sure to use the bind method, and everything seems to be referenced correctly. What am I missing here?
import React, {Component} from 'react';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
export default class CreateWorkout extends Component {
constructor(props) {
super(props); // Refers to the parent class constructorq
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeDescription = this.onChangeDescription.bind(this);
this.onChangeReps = this.onChangeReps.bind(this);
this.onChangeDuration = this.onChangeDuration.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username:'',
description: '',
reps: 0,
duration: 0,
date: new Date(),
users: []
}
}
componentDidMount() { // Invoked immediately after a component is mounted
this.setState({
users: ['test user'],
username: 'test user'
});
}
onChangeUsername(e) {
this.setState({
username: e.target.value
});
}
onChangeDescription(e) {
this.setState({
description: e.target.value
});
}
onChangeReps(e) {
this.setState({
reps: e.target.value
});
}
onChangeDuration(e) {
this.setState({
duration: e.target.value
});
}
onChangeDate(date) { // Need to add a date picker library for this
this.setState({
date: date
});
}
// Submit method for submitting an event of the form...
onSubmit(e) {
e.preventDefault();
const workout = {
username: this.state.username,
description: this.state.description,
reps: this.state.reps,
duration: this.state.duration,
date: this.state.date,
};
console.log(workout);
window.location = '/'; // After form is submitted, the location is updated so the user is taken back to the home page
}
render() {
return (
<div>
<h3>Create New Workout Log</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username: </label>
<select ref="userInput" required className="form-control" value={this.state.username} onChange={this.onChangeUsername}>
{
this.state.users.map(function(user) {
return <option key={user} value={user}>{user}</option>;
})
}
</select>
</div>
<div className="form-group">
<label>Description: </label>
<input type="text" required className="form-control" value={this.state.description} onChange={this.onChangeDescription}/>
</div>
<div className="form-group">
<label>Reps: </label>
<input type="text" className="form-control" value={this.state.reps} onChange={this.onChangeReps}/>
</div>
<div className="form-group">
<label>Duration: </label>
<input type="text" className="form-control" value={this.state.duration} onChange={this.onChangeDuration}/>
</div>
<div className="form-group">
<label>Date: </label>
<div><DatePicker selected={this.state.date} onChange={this.state.onChangeDate}/></div>
</div>
<div className="form-group">
<input type="submit" value="Create Workout Log" className="btn btn-primary"/>
</div>
</form>
</div>
);
}
}
I have created react components for a form. I passed data as props from GetSteps component to PageHeader component. Then I will able to use that data from the PageHeader. Also I passed same data from the GetSteps component to YourDetails component. But the data didn't pass to the YourDetails component. I cannot find the error. any help will be appreciated. Thank You.
class GetSteps extends React.Component {
constructor(props) {
super(props);
this.state = {data: ''}
}
// componentWillMount() {
// var lang = [];
// $.each(this.props.value.Languages, function(k, v) {
// return lang[k] = v;
// }.bind(this));
// this.setState({ data: this.props.value.Languages })
//
// console.log(this.state)
// }
render()
{
return (
<div className="page-content">
<div className="container">
<PageHeader title={this.props.value.Title} subtitle={this.props.value.SubTitle} f={this.props.value.PreferredLanguage}/>
<YourDetails title={this.props.value.Title} preferredlang={this.props.value.PreferredLanguage}></YourDetails>
</div>
</div>
);
}
}
this is where I pass data as props
function PageHeader(props){
return(
<div className="page-header">
<span className="page-header-icon icon-world"></span>
<h3 className="title">{props.title}</h3>
<h4 className="sub-title special">{props.subtitle}</h4>
</div>
);
}
this is where I get data from GetSteps component
class YourDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
havePartner: 'yes',
UserFirstName: "",
TravelPartnerName: "",
AmwayLocation: "",
Title: this.props.title
};
console.log(this.props);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleOptionChange = this.handleOptionChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
console.log(this.state);
event.preventDefault();
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'radio' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleOptionChange(event){
this.setState({
havePartner: event.target.value
});
}
render() {
return (
<div className="main-content">
<form onSubmit={this.handleSubmit}>
<div className="field dropdown requiredField">
<label className="left">
Your prefered language
</label>
<div className="middleColumn">
<select name="language"
value={this.props.preferredlang}
onChange={this.handleInputChange}
className="dropdown requiredField align--left">
<option defaultValue value={this.props.preferredlang}>{this.props.preferredlang}</option>
<option value='g'></option>
<option value='fdg'></option>
<option value='df'></option>
<option value='dfg'></option>
</select>
</div>
</div>
<div className="field requiredField align--left">
<label>
Your First Name
</label>
<input
name="UserFirstName"
type="text"
onChange={this.handleInputChange} />
</div>
<div className="field optionset requiredField travel-partner align--left">
<label className="left">
Did you have a travel partner?
</label>
<ul className="optionset requiredField travel-partner align--left">
<li>
<input type="radio" value="yes" checked={this.state.havePartner === 'yes'} onChange={this.handleOptionChange} className="radio"/>
<label>Yes</label>
</li>
<li>
<input type="radio" value="no" checked={this.state.havePartner === 'no'} onChange={this.handleOptionChange } className="radio"/>
<label>No</label>
</li>
</ul>
</div>
<div className="field text requiredField align--left">
<label className="left">
Your travel partner's first name
</label>
<input className="text requiredField align--left"
name="TravelPartnerName"
type="text"
onChange={this.handleInputChange} />
</div>
<div className="field text">
<label className="left requiredField">*Required Field</label>
</div>
<div className="Actions">
<button type="submit" value="Submit" className="action nolabel " >
<span>Proceed to Day 1</span>
<span className="progress"></span>
</button>
</div>
</form>
</div>
);
}
}
this is where I didn't get data from GetSteps component
class Step extends React.Component {
constructor(props) {
super(props);
this.state = {data: ''}
}
componentWillMount() {
var link = document.getElementById('step').getAttribute('link');
$.getJSON( link+"VideoBuildForm", function( data, status ) {
fieldValues.PreferredLanguage = data.compilation.PreferredLanguage;
fieldValues.AmwayLocation = data.location;
fieldValues.Languages =
$.each(data.languages, function(k, v) {
return data.languages[k] = v;
});
fieldValues.Title = data.title;
fieldValues.SubTitle = data.subtitle;
this.setState({ data: fieldValues });
}.bind(this));
}
render() {
return (
<div>
<GetSteps value={this.state.data}/>
</div>
);
}
}
this is where I pass data to the GetSteps component
Try using props.title in your constructor instead of this.props.title.
I have a child component with a select form element, this queries my API and makes a select box out of the data. I then try to pass the option back that's been selected via an OnChange function to my parent component so I can then send my data back to the server. I keep getting an error saying state is not defined, I am new to react and can't see where I am going wrong.
Here is my parent component
var ReactDom = require('react-dom');
const uuid = require('uuid/v1');
import {postDataTest} from "../actions/postData";
import TeamSelectBox from "./TeamSelectBox";
import React, {Component, PropTypes} from "react";
class PlayerForm extends Component {
constructor(props) {
super(props);
this.state = {
teamId: ''
};
this.handleChange = this.handleChange.bind(this);
}
fieldValues = {
name: null,
teamName: null,
bio: null
}
handleChange(dataFromChild) {
console.log(dataFromChild);
}
nextStep(e) {
e.preventDefault();
// Get values via this.refs
var player = {
id: uuid(),
name: ReactDom.findDOMNode(this.refs.name).value,
teamName: ReactDom.findDOMNode(this.refs.teamName).value,
bio: ReactDom.findDOMNode(this.refs.bio).value,
teamId: ReactDom.findDOMNode(this.refs.teamId).value
};
postDataTest(player);
}
render() {
return (
<div className="row">
<div className="col-md-6">
<div className="panel">
<div className="panel-heading">
<h1>Add Player</h1>
</div>
<div className="panel-body">
<form className="form-horizontal">
<div className="form-group">
<label className="control-label">Name</label>
<input type="text" className="form-control" ref="name" defaultValue={this.fieldValues.name}/>
</div>
<div className="form-group">
<label className="control-label">Team Name</label>
<input type="text" className="form-control" ref="teamName" defaultValue={this.fieldValues.teamName}/>
</div>
<TeamSelectBox state={this.state.teamId} onChange={this.handleChange}/>
<div className="form-group">
<label className="control-label">Bio</label>
<input type="textarea" className="form-control" ref="bio" defaultValue={this.fieldValues.bio}/>
</div>
<div className="bs-component">
<button className="btn btn-md btn-default btn-block" onClick={this.nextStep}>Save & Continue</button>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}
module.exports = PlayerForm;
And here is my child form select box
import React, {Component} from "react";
import axios from "axios";
import {postDataTest} from '../actions/postData';
class TeamSelectBox extends Component {
constructor(props) {
super(props);
this.state = {
teams: []
};
}
componentDidMount() {
axios.get("/api/teams")
.then(response => {
const teams = response.data;
this.setState({teams});
console.log(teams);
});
}
render() {
return (
<div className="form-group">
<label for="inputSelect" className="control-label">Select Team</label>
<div className="bs-component">
<select value={this.probs.state.teamId} onChange={this.probs.onChange} className="form-control">
<option value=""></option>
{this.state.teams.map(singleTeam =>
<option value={singleTeam.id}>{singleTeam.team.name}</option>
)}
</select>
</div>
</div>
);
}
}
export default TeamSelectBox;
Your approach seems OK, but you had a typo in your child Component:
{this.probs.onChange}
change it to {this.props.onChange} and try again!
i think you have a typo, you missed spell props, this.props not this.probs