React Form: Input Data Won't Display - reactjs

Every time I click the button a post is being created and displayed
But the input data isn't showing up
import React, { Component } from 'react'
export default class App extends Component {
state = {
dataArr : [],
isClicked: false,
title : '',
img : ''
}
handleSubmit = (e) => {
e.preventDefault()
}
handleChange = (e) => {
[e.target.name] = e.target.value
}
handleClick = () => {
const copyDataArr = Object.assign([], this.state.dataArr)
copyDataArr.push({
title : this.state.title,
img : this.state.img
})
this.setState({
isClicked : true,
dataArr : copyDataArr
})
}
render() {
console.log(this.state.title)
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="title" placeholder="Title.." onChange={this.handleChange}/>
<input type="text" name="img" placeholder="Image.." onChange={this.handleChange}/>
<button onClick={this.handleClick}>SUBMIT</button>
</form>
{ this.state.isClicked ?
this.state.dataArr.map(
(post, index) => {
return(
<div class="div">
<h1>title: {post.title}</h1>
<img src={post.img} alt="ohno"/>
</div>
)
}
)
: null }
</div>
)
}
}
Created an empty array on state and copied the array and pushed in the input values. What am I doing wrong?
Need the onChange to work and the input data to display
Trying to learn forms in react. Hope someone can help out

Your handleChange function is not updating state with the data you enter to the inputs. Looks like you might have forgotten to call this.setState(). Try this
:
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
Also here is a sandbox with the working code: https://codesandbox.io/s/distracted-darkness-xp3nu

You have to add a value attribute to the input tag and pass the state value.
<input type="text" name="title" value={this.state.title} placeholder="Title.." onChange={this.handleChange}/>
Your handle change function should be as follows
handleChange = (e) => {
this.setState({[e.target.name] : e.target.value});
}

Related

Why is React state not changing simultaneously with input change for a controlled component

I don't think I missed anything in making the form a controlled component. Why doesn't the state doesn't change as characters are being input?
class AddChores extends Component {
state = {
chore: "",
};
handleChange = (evt) => {
this.setState({ chore: evt.target.value });
};
handleSubmit = (evt) => {
evt.preventDefault();
this.props.addChores(this.state);
this.setState({ chore: "" });
};
render() {
console.log(this.state);
return (
<div>
<form onClick={this.handleSubmit}>
<input
type="text"
placeholder="New Chore"
value={this.state.chore}
onChange={this.handleChange}
/>
<button className="button">ADD CHORE</button>
</form>
</div>
);
}
}[![React dev tool showing no simultaneous update][1]][1]
I made some changes as below and it works fine for me. Hope it helps you too.
class AddChores extends Component {
constructor(props) {
super(props);
this.state = {
chore: ""
};
}
handleChange = (event) => {
this.setState({
chore: event.target.value
});
};
handleSubmit = (evt) => {
evt.preventDefault();
// this.props.addChores(this.state);
this.setState({ chore: "" });
};
componentDidUpdate(){
console.log('the state', this.state.chore)
}
render() {
return (
<div>
<form onClick={this.handleSubmit}>
<input
type="text"
placeholder="New Chore"
value={this.state.chore}
onChange={this.handleChange}
/>
</form>
</div>
);
}
}
not sure why is this happening but try using the second form of setState
this.setState(() => ({ chore: evt.target.value}))
check this https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Cannot update state with file uploader in reactJS

I created a simple image uploader component that is rendered in a new-image-form that extends a form. but when handling a change(an image upload), the state is updated with an empty opbject (and not with the file object). I tried to debug it but anything goes right until this.setState. Can anyone helps?
NewImagesForm :
class NewImagesForm extends Form {
state = {
data: {
_id: 0,
name: "",
file: null,
},
errors: {},
apiEndpoint: "",
};
render() {
return (
<div className="new-menu-item-form">
<form onSubmit={this.handleSubmit}>
{this.renderInput("name", "Name")}
{this.renderUploadFile("file", "Upload")}
{this.renderButton("Add")}
</form>
</div>
);
}
Form
class Form extends Component {
state = { data: {}, errors: {} };
handleFileUpload = (e) => {
const data = { ...this.state.data };
data[e.currentTarget.name] = e.target.files[0];
this.setState({ data });
};
renderUploadFile(name, label) {
const { data } = this.state;
return (
<UploadImage
name={name}
label={label}
value={data[name]}
onChange={this.handleFileUpload}
></UploadImage>
);
}
}
export default Form;
File Upload Component
const UploadImage = ({ name, label, error, onChange }) => {
return (
<div className="input-group">
<div className="custom-file">
<input
type="file"
onChange={onChange}
className="custom-file-input"
id={name}
name={name}
></input>
{label && (
<label className="custom-file-label" htmlFor={name}>
{label}
</label>
)}
</div>
<div className="input-group-append">
<button className="btn btn-outline-secondary" type="button">
Button
</button>
</div>
</div>
);
};
export default UploadImage;
First of all, react does not recommend the use of extends, because of the combination of extends.
In the Form component, the setState() trigger the render() , but there is no render(). setState does not allow renderUploadFile to be re-executed.
It would be a good idea to use the UploadImage component in the NewImagesForm component. Don't let NewImagesForm extends Form.
But the exactly same way works for me with custom input text and custom select boxes, see the differences:
handleChange = (e) => {
const data = { ...this.state.data };
data[e.currentTarget.name] = e.currentTarget.value;
this.setState({ data });
};
handleFileUpload = (e) => {
const data = { ...this.state.data };
data[e.currentTarget.name] = e.target.files[0];
this.setState({ data });
};

Input tag: nothing typed is appearing

My first React session data storage, so thanks. I am trying to set up inputing data and then placing it in session storage, so it can be edited, viewed or deleted later. There are 2 pieces of data, "title" and "note" to be inputed into a form. Nothing happens when I type into the form inputs. Any other help welcome also.
class AddNote extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
content: ''
}
}
componentDidMount() {
this.getFormData();
}
//let notes = getSessionItem(keys.notes);
//if (!notes) { notes = ""; }
onTitleChange(event) {
this.setState({ title: event.target.value }, this.storeFormData);
this.storeFormData();
}
onContentChange(event) {
this.setState({ content: event.target.value }, this.storeFormData);
}
storeFormData() {
const form = {
title: this.state.title,
content: this.state.content
}
setSessionItem(keys.user_form, form);
}
getFormData() {
const form = getSessionItem(keys.user_form);
if (form) {
this.setState({
title: form.name,
content: form.content
});
}
}
render() {
return (
<div>
<div>
<h2>ADD NOTE PAGE</h2>
</div>
<form classname="nav1">
<div>
<label><b>Title</b></label>
<input type="text"
value={this.state.title}
onchange={this.onTitleChange.bind(this)}
/>
</div>
<div>
<label><b>Content</b></label>
<input type="text"
value={this.state.content}
onchange={this.onContentChange.bind(this)}
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
export default AddNote;
and the storage file:
export const keys = {
title: 'title',
notes: 'notes'
}
export const getSessionItem = function (key) {
let item = sessionStorage.getItem(key);
item = JSON.parse(item);
return item;
}
export const setSessionItem = function (key, value) {
value = JSON.stringify(value);
sessionStorage.setItem(key, value);
}
export const removeSessionItem = function (key) {
sessionStorage.removeItem(key);
}
No need to have 2 change handler for your input. You can do it using a common change handler.
<form classname="nav1">
<div>
<label><b>Title</b></label>
<input type="text"
value={this.state.title}
name="title" <---- Provide name here
onChange={this.onChange}
/>
</div>
<div>
<label><b>Content</b></label>
<input type="text"
value={this.state.content}
name="content" <---- Provide name here
onChange={this.onChange}
/>
</div>
<button type="submit">Submit</button>
</form>
Your onChange function should be, and use callback in setState to call your storeFormData function.
onChange = (e) => {
this.setState({
[e.target.name] : e.target.value
}, () => this.storeFormData())
}
Note: In React we use camelCase, for example, onchange should be onChange and classname should be className.
Also make sure you bind this to storeFormData and getFormData functions, or you can use arrow function's to automatically bind this.
Demo

how to set state for input element created dynamically

I'm creating an input element using document.createElement and setting the attribute. i would like to have an onchange event which will update the state.
how can i proceed? following is my code
addoffers = () => {
var input = document.createElement("input");
input.setAttribute('name', 'whatweoffer'.concat(Math.floor((Math.random() * 1000) + 1)));
input.setAttribute('class','form-control mb-3');
input.setAttribute('placeholder','what we offer');
input.onchange = this.handleChange;
var parent = document.getElementById("offerinput");
parent.appendChild(input);
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(e.target.value);
}
<input type="text" className="form-control mb-3" id='whatweoffer' name='whatweoffer' onChange={this.handleChange} placeholder='what we offer' required />
Try this
class DynamicInputs {
constructor(props) {
super(props);
this.state = {
inputs : []
}
}
render() {
return (
<React.Fragment>
{
this.state.inputs.map(inputValue =>{
<input key= {inputValue} type="text" placeholder="what we offer" className="form-control mb-3" name = {`whatweoffer${inputValue}`} onChange = {this.handleChange} required/> })
}
</React.Fragment>
)
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(e.target.value);
}
addInput() = () =>{
let {inputs} = this.state;
inputs.push((Math.floor((Math.random() * 1000) + 1))
this.setState({
inputs
})
}
}
Although there's accepted answer but I want to give you another approach.
Instead of create input dynamically, why don't you just use own component's state to decide if an input is displayed or not, and other attributes are just state values. For example:
render() {
const {
isInputDisplayed, inputName, inputId, inputClasses, inputPlaceholder,
} = this.state;
return (
{ isInputDisplayed && (
<input type="text" name={inputName} id={inputId} className={inputClasses} placeholder={inputPlaceholder} />
)}
);
}

Updating State in textarea using controlled versus uncontrolled components

I'm trying to update a note and have both an input and textarea. I can update the state in my input just fine. However, only one additional character will update in my textarea. I know that it has to do with textarea being a controlled component and taking a value attribute rather than a defaultValue attribute. However, I can't seem to figure out what I'm doing wrong.
export default class UpdateNote extends Component {
constructor(props) {
super(props);
this.state = {
note: {},
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
submitHandler = (e) => {
e.preventDefault();
const note = {
title: this.state.title,
textBody: this.state.textBody,
};
const id = this.props.match.params.id;
axios
.put(`${URL}/edit/${id}`, note)
.then(response => {
this.setState({ title: '', textBody: '' })
this.setState({ note: response.data })
})
.catch(error => {
console.log(error)
})
}
render() {
return (
<div className="notes-list">
<h2 className="your-notes">Edit Note:</h2>
<form className="input-form" onSubmit={this.submitHandler} >
<input type="text" defaultValue={this.state.note.title} name="title" onChange={this.handleChange} />
<textarea type="textarea" value={this.state.note.textBody} name="textBody" onChange={this.handleChange} />
<button type="submit" className="submit-button">Update</button>
</form>
</div>
)
}
}

Resources