Enzyme: Value returns undefined when simulating onSubmit - reactjs

I'm trying to simulate the way the form was submitted. So to summarize when the user types in the textarea 'field, the component must be updated, then the user presses the submit button and the component is updated again. I expect that the value filled in the textarea will be empty after the user successfully submit. But unexpectedly the returned value is undefined.
CommentBox.js
import React from 'react';
class CommentBox extends React.Component {
state = {
comment: ''
}
handleChange = event => {
this.setState({
comment: event.target.value
})
}
handleSubmit = event => {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h4>Add a comment</h4>
<textarea onChange={this.handleChange} value={this.state.comment} />
<div>
<button>Submit Comment</button>
</div>
</form>
)
}
}
export default CommentBox;
CommentBox.text.js
import React from 'react';
import { mount } from 'enzyme';
import CommentBox from 'components/CommentBox';
let wrapped;
beforeEach(() => {
wrapped = mount(<CommentBox />);
})
afterEach(() => {
wrapped.unmount();
})
it('when form is submitted, text area gets emptied', () => {
wrapped.find('textarea').simulate('change', {
target: { value: 'new comment' }
})
wrapped.update();
wrapped.find('form').simulate('submit', {
preventDefault: () => {}
});
wrapped.update();
expect(wrapped.find('textarea').prop('value')).toEqual('');
})
I expect the output will be passed but the actual output is value returns undefined so test is failed.

I don't see anything that would make the test fail... other than not including this.setState({ comment: "" }); in the handleSubmit callback.
If you utilize state, then you have to manually reset it (or if the component unmounts, then it loses state automatically). React works by manipulating a virtual DOM. Then, you utilize state to manipulate the elements within this virtual DOM. Since you're preventing a page refresh (e.preventDefault) the state persists as intended.
Working example (click the Tests tab -- next to the Browser tab -- to run the test):
components/CommentBox
import React, { Component } from "react";
class CommentBox extends Component {
state = { comment: "" };
handleChange = ({ target: { value } }) => {
this.setState({ comment: value });
};
handleSubmit = e => {
e.preventDefault();
console.log("submitted comment: ", this.state.comment);
this.setState({ comment: "" });
};
render = () => (
<div className="app">
<form onSubmit={this.handleSubmit}>
<h4>Add a comment</h4>
<textarea
className="uk-textarea"
onChange={this.handleChange}
value={this.state.comment}
/>
<div className="button-container">
<button type="submit" className="uk-button uk-button-primary">
Submit Comment
</button>
</div>
</form>
</div>
);
}
export default CommentBox;
components/CommentBox/__tests__/CommentBox.test.js
import React from "react";
import { mount } from "enzyme";
import CommentBox from "../index";
describe("Comment Box", () => {
let wrapper;
beforeEach(() => {
wrapper = mount(<CommentBox />);
});
afterEach(() => {
wrapper.unmount();
});
it("when form is submitted, text area gets emptied", () => {
wrapper.find("textarea").simulate("change", {
target: { value: "new comment" }
});
expect(wrapper.find("textarea").prop("value")).toEqual("new comment");
wrapper.find("form").simulate("submit", {
preventDefault: () => {}
});
expect(wrapper.find("textarea").prop("value")).toEqual("");
});
});

handleChange = (e) => {
if(e.keyCode == 13 && e.shiftKey == false) {
e.preventDefault();
this.myFormRef.submit();
}
}
render() {
return (
<form ref={el => this.myFormRef = el} >
<h4>Add a comment</h4>
<textarea onKeyDown={this.handleChange} value={this.state.comment}
/>
<div>
<button type="submit">Submit Comment</button>
</div>
</form>
);
}
you can do like this on enter

You may try this:
import React from 'react';
class CommentBox extends React.Component {
//adding initVal for setting initial value in textbox
// and playing with it until the form submits
state = {
comment: '',
initVal: ''
}
handleChange = event => {
//on change in textfield, updating initVal with the typed text
this.setState({
initVal: event.target.value
})
}
handleSubmit = event => {
//finally on submission comment is updated with entered value
//which you may use it for further operations
//and initVal is set back to empty '' for setting textfield value as empty
//field
this.setState({
comment: this.state.initVal
initVal: ''
})
//event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h4>Add a comment</h4>
//changes here
<textarea onChange={this.handleChange} value={this.state.initVal} />
<div>
<button>Submit Comment</button>
</div>
</form>
)
}
}
export default CommentBox;

Related

How to transform this function component into a class component? (React.js)

I am new to React and struggle to transform this function component into a class component with a constructor(). I can't figure out how to transform the functions happening onSubmit and onClick.
Thank you very much.
The function component:
import React, { useState, Component } from 'react';
import { render } from 'react-dom';
import './Options.css';
const Test = (props) => {
const [links, setLinks] = useState([]);
const [link, setLink] = useState('');
function handleSubmit(e) {
e.preventDefault();
const newLink = {
id: new Date().getTime(),
text: link,
};
setLinks([...links].concat(newLink));
setLink('');
}
function deleteLink(id) {
const updatedLinks = [...links].filter((link) => link.id !== id);
setLinks(updatedLinks);
}
return (
<div className="OptionsContainer">
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => setLink(e.target.value)}
value={link}
/>
<button type="submit"> + </button>
</form>
{links.map((link) => (
<div key={link.id}>
<div>{link.text}</div>
<button onClick={() => deleteLink(link.id)}>Remove</button>
</div>
))}
</div>
);
};
export default Test;
When we work with class components a couple of things got changed, we have a new object this.state, a new function this.setState, you have to bind your functions on the constructor if you want to have access to this inside it. I think you'll learn way more if you read the code, so here this is your component as a class component:
import React, { Component } from 'react';
import './Options.css';
class App extends Component {
constructor() {
super()
this.state = {
links: [],
link: '',
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const newLink = {
id: new Date().getTime(),
text: this.state.link,
};
this.setState({links: [...this.state.links, newLink], link: ''});
}
deleteLink(id) {
const updatedLinks = [...this.state.links].filter((link) => link.id !== id);
this.setState({...this.state, links: updatedLinks });
}
render() {
console.log(this.state)
return (
<div className="OptionsContainer">
<form onSubmit={this.handleSubmit}>
<input
type="text"
onChange={(e) => this.setState({ ...this.state, link: e.target.value})}
value={this.state.link}
/>
<button type="submit"> + </button>
</form>
{this.state.links.map((link, index) => (
<div key={link.id}>
<span>{link.text}</span>
<button onClick={() => this.deleteLink(link.id)}>Remove</button>
</div>
))}
</div>
);
}
};
export default Test;
Without seeing your original functional component, it's going to be hard to tell you what the class component should look like.
To answer your question about why onSubmit might not be working, it's because onSubmit is expecting to be passed an uncalled function, so that the <form> element can call that function itself when the time is right.
You are currently calling the function this.handleOnSubmit(), which returns nothing, so no handler for the form submit is properly assigned. Try removing the call to the function, like this:
<form onSubmit={this.handleSubmit}>

Cannot get input value on submit function

I am trying to display input value on submit. But it seems to be not working. I don't have any errors but nothing being rendered. What is wrong with the code?
import React from 'react';
import { Component } from 'react';
class App extends Component {
constructor (props) {
super(props)
this.state = {
city : ""
}
}
handleSubmit = (event)=> {
event.preventDefault();
this.setState ({
city : event.target.value
})
}
render () {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type = "text" city = "city_name" />
<button type="submit">Get Weather</button>
{this.state.city}
</form>
</div>
)
}
}
export default App;
<form
onSubmit={e=>{
e.preventDefault()
console.log(e.target[0].value)
}}>
<input type="text"/>
<button type="submit">dg</button>
</form>
that works for me very well
Remember onSubmit target:
Indicates where to display the response after submitting the form. So you can get inner elements (and their corresponding values) like normal javascript code.
const city = event.target.querySelector('input').value
handleSubmit = (event) => {
event.preventDefault();
this.setState ({ city })
}
I guess you want it to get work like below. But this is not the only way to get it done.
import React from "react";
import { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
}
handleSubmit = (event) => {
const formData = new FormData(event.currentTarget);
event.preventDefault();
let formDataJson = {};
for (let [key, value] of formData.entries()) {
formDataJson[key] = value;
}
this.setState(formDataJson);
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="city" />
<button type="submit">Get Weather</button>
{this.state.city}
</form>
</div>
);
}
}
export default App;
Code sandbox => https://codesandbox.io/s/eager-oskar-dbhhu?file=/src/App.js

How can I make the text area empty after I click the submit button?

How can I make the text area empty after I click the submit button??
Im trying to create a simple form submit in react. Can you please tell me how can i make the text area empty after I click the Submit button. This is my problem.
This is my App.js code:
import React, { Component } from 'react'
import Textarea from "./Textarea";
import Button from "./Button";
export class App extends Component {
constructor(){
super();
this.state = {
Tinput: '',
// Ninput:'',
submit: ''
}
}
changeHandle = (event) => {
this.setState({
Tinput: event.target.value
})
}
submitHandle = (event) => {
event.preventDefault();
this.setState({
submit: this.state.Tinput
})
}
resetHandle = (event) => {
event.preventDefault();
this.setState(
{submit: ''}
)
}
// handleKeypress = (event) => {
// if (event.keyCode === 'Enter') {
// this.submitHandle();
// }
// }
render() {
return (
<div>
<div>
<Textarea changeHandle={this.changeHandle} change={this.state.Tinput}/>
<Button action={this.submitHandle} name="submit"/>
<Button action={this.resetHandle} name="Reset" />
</div>
<p>{this.state.submit}</p>
</div>
)
}
}
export default App
This is my Textarea.js code:
import React from 'react'
const Textarea = (props) => {
return (
<div>
<textarea
type="text"
onChange={props.changeHandle}
// onKeyPress={this.handleKeypress}
value={props.change}
className="form-control"
id="exampleFormControlTextarea1" rows="3"
placeholder='write something here'
/>
</div>
);
}
export default Textarea;
This is my button.js code:
import React from 'react'
const Button = (props) => {
return (
<div>
<button type="submit" className="btn btn-primary" onClick={props.action}>{props.name}</button>
</div>
);
}
export default Button;
You can set it as empty in submit function
submitHandle = (event) => {
event.preventDefault();
this.setState({
submit: this.state.Tinput,
Tinput:""
})
}
Try this :
submitHandle = (event) => {
event.preventDefault();
this.setState({
submit: this.state.Tinput,
Tinput: '',
})
}

duplicates being created in todo list app

I am creating a todo list where when the user clicks the checkbox "complete" that is next to the todo item, it appears in the complete component however there is a duplicate of that item that is being added as well and i am also having an issue trying to have the checkbox not appear in the completed component...
When a user creates a new todo it appears in the active component first and it has a checkbox next to it called completed and when the user clicks the checkbox it appears in the completed component
import React from 'react';
import Active from './Components/Active';
import Completed from './Components/Completed';
import Todoform from './Components/Todoform';
import './App.css';
class App extends React.Component {
state = {
items: [],
task: '',
id: 0,
completedItems: []
}
handleInput = (event) => {
this.setState({
task: event.target.value
})
}
handleSubmit = (event) => {
event.preventDefault()
const newTask = {
id: this.state.id,
title: this.state.task
}
const updatedItems = [...this.state.items, newTask]
this.setState({
items: updatedItems,
task: '',
id: this.state.id + 1
})
}
handleComplete = (newTask) => {
this.setState({completedItems: [...this.state.items, newTask]})
//console.log(this.state.items)
}
render() {
return (
<div id="main-content">
<h1>Task Lister</h1>
<Todoform
handleChange={this.handleInput}
handleSubmit={this.handleSubmit}
task={this.state.task}
/>
<Active
items={this.state.items}
handleComplete={this.handleComplete}
/>
<Completed
completedItems={this.state.completedItems}
/>
</div>
)
}
}
export default App;
import React from 'react'
class Todo extends React.Component{
state = {
checked: false
}
handleCheck = () => {
this.setState({
checked: !this.state.checked
})
}
handleClick = () => {
this.props.handlecompletedList(this.props.title)
}
render(){
const { title } = this.props
return (
<div className="ui checked checkbox">
<input type="checkbox" checked={this.state.checked} onChange={this.handleCheck}
onClick={this.handleClick}/>
<label>Completed {title}</label>
</div>
)
}
}
export default Todo;
import React from 'react'
import Todo from './Todo'
const Active = (props) => {
const { items, handleComplete } = props
return(
<div id="activeList">
<h2 className="position">Active</h2>
<ul id="tasks">
{
items.map(item => {
return(
<Todo key={item.id} handlecompletedList={handleComplete} title={item.title}/>
)
})
}
</ul>
</div>
)
}
export default Active;
import React from 'react'
import Todo from './Todo'
const Completed = (props) => {
const { completedItems } = props
return(
<div id="completedList">
<h2 className="position">Completed</h2>
<ul id="tasks">
{
completedItems.map(item => {
return(
<Todo key={item.id} title={item.title}/>
)
})
}
</ul>
</div>
)
}
export default Completed
import React from 'react';
class Todoform extends React.Component {
render(){
const {task, handleChange, handleSubmit} = this.props;
return(
<form onSubmit={handleSubmit}>
<label>Task description:</label>
<input type="text" name="name" placeholder="description" value={task} onChange={handleChange}/>
<button>Create New Task</button>
</form>
)
}
}
export default Todoform;
To hide the checkbox next to completed items you need to use Conditional Rendering. An example would be to add a prop IsCompleted to your component and use it when rendering html like this:
{this.props.isCompleted &&
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheck}
onClick={this.handleClick}/>
}
The duplicate item issue is probably because you use this.state.items in your handleComplete method instead of using this.state.completedItems if this is not the issue, would you mind sharing the code for the Todoform component as well?
EDIT: The item duplicates because when the handleComplete is called it copies this.state.items to the list and adds the one that you clicked on.
You should use this.state.completedItems in the handleComplete, also you are currently only sending and appending the title in the handleComplete method, you should be appending an object that has a title. The solution would be to update your handleClick method to this and update handleComplete to use this.state.completedItems:
handleClick = () => {
this.props.handlecompletedList({
title: this.props.title
});
};

React setState doesn't update the state after submitting input form

I am new in React and want to develop easy app - there is input field from which I want to take values and render list. After added option in text field I want to update this list whith new option.
setState function does not work and I don't know how to connect input submit and list rendering. My code is below.
WaterApp.js
import React from 'react';
import AddWater from './AddWater';
import WaterElements from './WaterElements';
export default class WaterApp extends React.Component {
state = {
quantities: ['aaaaa', 'bbbbb', 'ccccc']
};
handleAddQuantity = (quantity) => {
this.setState(() => ({
quantities: ['ddddd', 'eeeee']
}));
console.log('works');
}
render() {
return (
<div>
<WaterElements quantities={this.state.quantities} />
<AddWater handleAddQuantity={this.handleAddQuantity} />
</div>
)
}
}
AddWater.js
import React from 'react';
export default class AddWater extends React.Component {
handleAddQuantity = (e) => {
e.preventDefault();
const quantity = e.target.elements.quantity.value;
console.log(quantity);
};
render() {
return (
<form onSubmit={this.handleAddQuantity}>
<input type="text" name="quantity" />
<input type="submit" value="Submit" />
</form>
)
}
}
WaterElements.js
import React from 'react';
const WaterElements = (props) => (
<div>
<p>Water Quantity:</p>
{
props.quantities.map((quantity) =>
<p key={quantity}>{quantity}</p>
)
}
</div>
);
export default WaterElements;
I expect list to be ddddd, eeeee at this moment.
You're never calling props.handleAddQuantity
export default class AddWater extends React.Component {
handleAddQuantity = (e) => {
e.preventDefault();
const quantity = e.target.elements.quantity.value;
props.handleAddQuantity(quantity)
};
render() {
return (
<form onSubmit={this.handleAddQuantity}>
<input type="text" name="quantity" />
<input type="submit" value="Submit" />
</form>
)
}
this.setState(() => ({
quantities: ['ddddd', 'eeeee']
}));
should be
this.setState({
quantities: ['ddddd', 'eeeee']
});
and after for add
this.setState({
quantities: [...state.quantities, quantity]
});
to update use this format
this.state({key:value});
not this.state(()=>{key:value});
handleAddQuantity = (quantity) => {
this.setState({
quantities: ['ddddd', 'eeeee']
}));
console.log('works');
}

Resources