React setState from multiple input boxes - forms

I'm working on a Recipe Box project and I have a program that allows the user to click a button which then displays input boxes that allows the user to add a new recipe to a list.
I have two inputs in the form. One for the name of the recipe being added, and one for the ingredients. The input for the name of the recipe works and allows the user to add a name, but the second input box is not updating the ingredients in state as it should.
Why isn't ingredientVal being updated in state? Why can't I enter text in the second input box?
import React, { Component } from 'react';
import RecipeList from './RecipeList';
import './App.css';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: ["Pumpkin Pie", "Spaghetti", "Onion Pie"],
ingredients:[
["Pumpkin Puree", "Sweetened Condensed Milk", "Eggs", "Pumpkin Pie Spice", "Pie Crust"],
["Noodles", "Tomato Sauce", "(Optional) Meatballs"],
["Onion", "Pie Crust"]
],
inputVal: '',
ingredientVal: '',
showRecipe: false
};
}
// Get text user inputs for recipe
handleChange = (event) => {
this.setState({inputVal: event.target.value});
};
handleIngredientChange = (event) => {
this.setState({ingredientVal: event.target.value});
}
// When user submits recipe this adds it
onSubmit = (event) => {
event.preventDefault()
this.setState({
inputVal: '',
items: [...this.state.items, this.state.inputVal],
ingredientVal: '',
ingredients: [...this.state.ingredients, this.state.ingredientVal]
});
}
onIngredientSubmit = (event) => {
event.preventDefault()
this.setState({
ingredientVal: '',
ingredients: [...this.state.ingredients, this.state.ingredientVal]
});
}
// Shows recipe
AddRecipe = (bool) => {
this.setState({
showRecipe: bool
});
}
render() {
return (
<div className="App">
<h3>Recipe List</h3>
<RecipeList items={this.state.items} ingredients={this.state.ingredients} />
<button onClick={this.AddRecipe}>Add New Recipe</button>
{ this.state.showRecipe ?
<div>
<form className="Recipe-List" onSubmit={this.onSubmit}>
<div className="Recipe-Item">
<label>Recipe Name</label>
<input
value={this.state.inputVal}
onChange={this.handleChange} />
</div>
<div className="Recipe-Item">
<label>Ingredients</label>
<input
value={this.state.ingredientVal}
onChange={this.state.handleIngredientChange} />
</div>
<button>Submit</button>
</form>
</div>
:null
}
</div>
);
}
}

You're calling this.state.handleIngredientChange as your onChange when it should be this.handleIngredientChange

Related

How to change the input value in a form with react and redux?

I am creating my edit form with react-redux.
Until now, I can get the data of the item that I want to change, but I do not know how to pre-populate the input value, and to be able to change it.
Because when I try to tape something in the input, the text does not change.
So, how can I pre-populate the input value, and being able to tape into it.
import React from 'react';
import PropTypes from 'prop-types';
class EditTodoComponent extends React.Component {
state = {
text: this.props.todo.text
}
onChange(e) {
this.setState({ text: e.target.value });
}
render() {
return(
<div>
<form>
<input type="text" value={this.state.text} onChange={this.onChange}/>
</form>
</div>
);
}
}
EditTodoComponent.propTypes = {
todo: PropTypes.shape({
id: PropTypes.number.isRequired,
completed: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}).isRequired,
visible: PropTypes.bool.isRequired
}
export default EditTodoComponent
Try this
import React from 'react';
import PropTypes from 'prop-types';
class EditTodoComponent extends React.Component {
constructor() {
super();
this.state = {
text: this.props.todo.text
}
this.defaultText = "default string";
}
onChange(e) {
this.setState({ text: e.target.value });
}
render() {
return(
<div>
<form>
<input
type="text"
value= {this.state.text
? this.defaultText
: this.state.text
}
onChange={this.onChange}/>
</form>
</div>
);
}
}
EditTodoComponent.propTypes = {
todo: PropTypes.shape({
id: PropTypes.number.isRequired,
completed: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}).isRequired,
visible: PropTypes.bool.isRequired
}
export default EditTodoComponent
Check this.state.text value, if it's null then use defaultValue instead.
Try with this:
import React from 'react';
import PropTypes from 'prop-types';
class EditTodoComponent extends React.Component {
constructor() {
super();
this.state = {
text: this.props.todo.text
};
this.defaultText = "default string";
}
onChange(e) {
this.setState({ text: e.target.value });
}
render() {
return(
<div>
<form>
<input type="text" value={this.state.text || this.defaultText} onChange={(e) => this.onChange(e)}/>
</form>
</div>
);
}
}
You were missing the constructor definition and the onChange was wrongli bound so that this was not the component itself

Reactjs how to get value from selected element

so I have this code for posting to my backend API. Normal form perfectly fine; I managed to post to my database. So I add a Cascader from Ant Design CSS Framework, and every time I selected the value, it produced an error
TypeError: Cannot read property 'value' of undefined
Here is the code:
import React from 'react';
import axios from 'axios';
import { Button, Cascader, Form, Input, Modal } from 'antd';
const FormProduct = Form.Item;
const computerType = [
{
value: 'computer',
label: 'Computer',
},
{
value: 'laptop',
label: 'Laptop',
}
]
export default class FormInventory extends React.Component {
state = {
category: '',
productname: '',
};
handleCategoryChange = event => { this.setState({ category: event.target.value }) }
handleProductNameChange = event => { this.setState({ productname: event.target.value }) }
handleSubmit = event => {
event.preventDefault();
axios.post('myapi',
{
category: this.state.category,
productname: this.state.productname,
})
.then(
function success() {
const modal = Modal.success({
title: 'Success',
content: 'Data successfully add',
});
setTimeout(() => modal.destroy(), 2000);
}
)
}
render() {
return (
<Form onSubmit={this.handleSubmit}>
<FormProduct {...formProductLayout} label="Computer Category">
<Cascader options={computerType} category={this.state.value} onChange={this.handleCategoryChange} />
</FormProduct>
<FormProduct {...formProductLayout} label="Product Name">
<Input type="text" productname={this.state.productname} onChange={this.handleProductNameChange} />
</FormProduct>
<FormProduct wrapperCol={{ span: 12, offset: 2 }}>
<Button type="primary" htmlType="submit">
Add Item
</Button>
</FormProduct>
</Form>
)
}
}
You need to either bind your event handlers in the constructor or use arrow function.
Option 1: Bind
constructor(props) {
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
Option 2: Arrow function
<Input onChange={(e) => this.handleChange(e)} />
According to antd docs you don't need event.target.
https://ant.design/components/cascader/
handleCategoryChange = category => { this.setState({ category }) }
The code above will work fine.

ReactJS Semantic ui - Cannot type into form when value attribute exists

I am following a ReactJS tutorial to set up a login form. Semantic ui is used and imported. The email and password are passed into the value attribute inside the form. When this happens, I cannot type anything into the form. As soon as I remove it, I can type information in but I assume it won't get passed into anywhere.
Cannot seem to find this issues anywhere else. Has anyone experienced this issue before?
import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'semantic-ui-react';
import Validator from 'validator';
import InlineError from '../messages/InlineError';
class LoginForm extends React.Component {
state = {
data: {
email: "",
password: ""
},
loading: false,
errors: {}
};
//... is called spread
onChange = e => this.setState({
data: {...this.state.data, [e.target.name]: e.target.value }
});
//() means function takes no params
onSubmit = () => {
const errors = this.validate(this.state.data);
this.setState({errors}); //if there are errors, display them
if(Object.keys(errors).length === 0){
this.props.submit(this.state.data);
}
};
validate = (data) => {
const errors = {};
if(!Validator.isEmail(data.email))
errors.email = "Invalid email";
if(!data.password)
errors.password = "Can't be blank";
return errors;
};
render() {
const { data, errors } = this.state; // import variables into html
return (
<div>
<Form onSubmit={ this.onSubmit }>
<Form.Field error={!!errors.email}>
<label htmlFor="email">Email</label>
<input type="email"
id="email"
placeholder="example#abc.com"
value={ data.email }
onChange={ this.onChange }/>
{errors.email && <InlineError text={errors.email}/>}
</Form.Field>
<Form.Field error={!!errors.email}>
<label htmlFor="password">Password</label>
<input type="password"
id="password"
value={ data.password }
onChange={this.onChange}/>
{errors.password && <InlineError text={errors.password}/>}
</Form.Field>
<Button primary>Login</Button>
</Form>
</div>
);
}
}
LoginForm.propTypes = {
submit: PropTypes.func.isRequired
};
export default LoginForm;
tutorial: https://www.youtube.com/watch?v=NO2DaxhoWHk&t=879s
onChange = e => this.setState({
data: {...this.state.data, [e.target.name]: e.target.value }
});
This function is setting the state to a variable that shares the name of your input field. Hence e.target.name. But your input fields do not have a name attribute.
You can fix that with:
import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'semantic-ui-react';
import Validator from 'validator';
import InlineError from '../messages/InlineError';
class LoginForm extends React.Component {
state = {
data: {
email: "",
password: ""
},
loading: false,
errors: {}
};
//... is called spread
onChange = e => this.setState({
data: {...this.state.data, [e.target.name]: e.target.value }
});
//() means function takes no params
onSubmit = () => {
const errors = this.validate(this.state.data);
this.setState({errors}); //if there are errors, display them
if(Object.keys(errors).length === 0){
this.props.submit(this.state.data);
}
};
validate = (data) => {
const errors = {};
if(!Validator.isEmail(data.email))
errors.email = "Invalid email";
if(!data.password)
errors.password = "Can't be blank";
return errors;
};
render() {
const { data, errors } = this.state; // import variables into html
return (
<div>
<Form onSubmit={ this.onSubmit }>
<Form.Field error={!!errors.email}>
<label htmlFor="email">Email</label>
<input type="email"
id="email"
name="email"
placeholder="example#abc.com"
value={ data.email }
onChange={ this.onChange }/>
{errors.email && <InlineError text={errors.email}/>}
</Form.Field>
<Form.Field error={!!errors.email}>
<label htmlFor="password">Password</label>
<input type="password"
id="password"
name="password"
value={ data.password }
onChange={this.onChange}/>
{errors.password && <InlineError text={errors.password}/>}
</Form.Field>
<Button primary>Login</Button>
</Form>
</div>
);
}
}
LoginForm.propTypes = {
submit: PropTypes.func.isRequired
};
export default LoginForm;

Form fields lose focus when input value changes

I'm trying to build a form with conditional fields from a JSON schema using react-jsonschema-form and react-jsonschem-form-conditionals.
The components I'm rendering are a FormWithConditionals and a FormModelInspector. The latter is a very simple component that shows the form model.
The relevant source code is:
import React from 'react';
import PropTypes from 'prop-types';
import Engine from "json-rules-engine-simplified";
import Form from "react-jsonschema-form";
import applyRules from "react-jsonschema-form-conditionals";
function FormModelInspector (props) {
return (
<div>
<div className="checkbox">
<label>
<input type="checkbox" onChange={props.onChange} checked={props.showModel}/>
Show Form Model
</label>
</div>
{
props.showModel && <pre>{JSON.stringify(props.formData, null, 2)}</pre>
}
</div>
)
}
class ConditionalForm extends React.Component {
constructor (props) {
super(props);
this.state = {
formData: {},
showModel: true
};
this.handleFormDataChange = this.handleFormDataChange.bind(this);
this.handleShowModelChange = this.handleShowModelChange.bind(this);
}
handleShowModelChange (event) {
this.setState({showModel: event.target.checked});
}
handleFormDataChange ({formData}) {
this.setState({formData});
}
render () {
const schema = {
type: "object",
title: "User form",
properties: {
nameHider: {
type: 'boolean',
title: 'Hide name'
},
name: {
type: 'string',
title: 'Name'
}
}
};
const uiSchema = {};
const rules = [{
conditions: {
nameHider: {is: true}
},
event: {
type: "remove",
params: {
field: "name"
}
}
}];
const FormWithConditionals = applyRules(schema, uiSchema, rules, Engine)(Form);
return (
<div className="row">
<div className="col-md-6">
<FormWithConditionals schema={schema}
uiSchema={uiSchema}
formData={this.state.formData}
onChange={this.handleFormDataChange}
noHtml5Validate={true}>
</FormWithConditionals>
</div>
<div className="col-md-6">
<FormModelInspector formData={this.state.formData}
showModel={this.state.showModel}
onChange={this.handleShowModelChange}/>
</div>
</div>
);
}
}
ConditionalForm.propTypes = {
schema: PropTypes.object.isRequired,
uiSchema: PropTypes.object.isRequired,
rules: PropTypes.array.isRequired
};
ConditionalForm.defaultProps = {
uiSchema: {},
rules: []
};
However, every time I change a field's value, the field loses focus. I suspect the cause of the problem is something in the react-jsonschema-form-conditionals library, because if I replace <FormWithConditionals> with <Form>, the problem does not occur.
If I remove the handler onChange={this.handleFormDataChange} the input field no longer loses focus when it's value changes (but removing this handler breaks the FormModelInspector).
Aside
In the code above, if I remove the handler onChange={this.handleFormDataChange}, the <FormModelInspector> is not updated when the form data changes. I don't understand why this handler is necessary because the <FormModelInspector> is passed a reference to the form data via the formData attribute. Perhaps it's because every change to the form data causes a new object to be constructed, rather than a modification of the same object?
The problem is pretty straightforward, you are creating a FormWithConditionals component in your render method and in your onChange handler you setState which triggers a re-render and thus a new instance of FormWithConditionals is created and hence it loses focus. You need to move this instance out of render method and perhaps out of the component itself since it uses static values.
As schema, uiSchema and rules are passed as props to the ConditionalForm, you can create an instance of FormWithConditionals in constructor function and use it in render like this
import React from 'react';
import PropTypes from 'prop-types';
import Engine from "json-rules-engine-simplified";
import Form from "react-jsonschema-form";
import applyRules from "react-jsonschema-form-conditionals";
function FormModelInspector (props) {
return (
<div>
<div className="checkbox">
<label>
<input type="checkbox" onChange={props.onChange} checked={props.showModel}/>
Show Form Model
</label>
</div>
{
props.showModel && <pre>{JSON.stringify(props.formData, null, 2)}</pre>
}
</div>
)
}
class ConditionalForm extends React.Component {
constructor (props) {
super(props);
this.state = {
formData: {},
showModel: true
};
const { schema, uiSchema, rules } = props;
this.FormWithConditionals = applyRules(schema, uiSchema, rules, Engine)(Form);
this.handleFormDataChange = this.handleFormDataChange.bind(this);
this.handleShowModelChange = this.handleShowModelChange.bind(this);
}
handleShowModelChange (event) {
this.setState({showModel: event.target.checked});
}
handleFormDataChange ({formData}) {
this.setState({formData});
}
render () {
const FormWithConditionals = this.FormWithConditionals;
return (
<div className="row">
<div className="col-md-6">
<FormWithConditionals schema={schema}
uiSchema={uiSchema}
formData={this.state.formData}
onChange={this.handleFormDataChange}
noHtml5Validate={true}>
</FormWithConditionals>
</div>
<div className="col-md-6">
<FormModelInspector formData={this.state.formData}
showModel={this.state.showModel}
onChange={this.handleShowModelChange}/>
</div>
</div>
);
}
}
ConditionalForm.propTypes = {
schema: PropTypes.object.isRequired,
uiSchema: PropTypes.object.isRequired,
rules: PropTypes.array.isRequired
};
ConditionalForm.defaultProps = {
uiSchema: {},
rules: []
};
For anyone bumping into the same problem but using Hooks, here's how without a class :
Just use a variable declared outside the component and initialize it inside useEffect. (don't forget to pass [] as second parameter to tell react that we do not depend on any variable, replicating the componentWillMount effect)
// import ...
import Engine from 'json-rules-engine-simplified'
import Form from 'react-jsonschema-form'
let FormWithConditionals = () => null
const MyComponent = (props) => {
const {
formData,
schema,
uischema,
rules,
} = props;
useEffect(() => {
FormWithConditionals = applyRules(schema, uischema, rules, Engine)(Form)
}, [])
return (
<FormWithConditionals>
<div></div>
</FormWithConditionals>
);
}
export default MyComponent
Have you tried declaring function FormModelInspector as an arrow func :
const FormModelInspector = props => (
<div>
<div className="checkbox">
<label>
<input type="checkbox" onChange={props.onChange} checked={props.showModel}/>
Show Form Model
</label>
</div>
{
props.showModel && <pre>{JSON.stringify(props.formData, null, 2)}</pre>
}
</div>
)

unable set a default value in redux-form w. react

I'm unable to set a default value of a form w/redux-form. The result I'm looking for is an editable text field to later to submit to the database. i.e. updating an email address.
I've tried setting a property in the form to value or defaultValue.
Note: I've taken repetitive code out to make this easier to read with just a "name" field.
any insight is appreciated!
import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
export const fields = [ 'name']
//(container) page-profile.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Profile from '../components/Profile';
class PageProfile extends Component {
render() {
return (
<Profile
userInfo = {this.props.userInfo}
/>
)
}
}
// requiring this page before rendering -- breaks page
PageProfile.propTypes = {
//userInfo: PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {
userInfo : state.auth.userInfo
}
}
// injection to child
export default connect(mapStateToProps, {
})(PageProfile);
// profile.js
export default class Profile extends Component {
render() {
const { fields: {name }, resetForm, handleSubmit, submitting } = this.props
return (
<div>
<img className="image" src={this.props.userInfo.img_url}/>
<form onSubmit={handleSubmit}>
<div>
<div>
<label>name</label>
<div>
<input type="text" defaultValue={this.props.userInfo.name} placeholder="name" {...name}/>
</div>
{name.touched && name.error && <div>{name.error}</div>}
</div>
<button type="submit" disabled={submitting}>
{submitting ? <i/> : <i/>} Submit
</button>
</form>
</div>
)
}
}
Profile.propTypes = {
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
resetForm: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired
}
export default reduxForm({
form: 'Profile',
fields,
validate
})(Profile)
You can supply initialValues in reduxForm's mapStateToProps:
const mapFormToProps = {
form: 'Profile',
fields,
validate
};
const mapStateToProps = (state, ownProps) => ({
initialValues: {
name: ownProps.userInfo.name
}
});
reduxForm(
mapFormToProps,
mapStateToProps
)(Profile)
Then just bind like so: <input type="text" placeholder="name" {...name} />.