What causes a horizontal line to form when a user enters white space?

I have written a piece of code which seems to be causing an issue when running it. Whenever I input empty spaces, it results in creating a horizontal line.

import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
    super(props);
    this.state = { items: [], text: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
} 

render() {
    return (
      <div>
        <form onSubmit  = {this.handleSubmit}>
          <input 
            onChange={this.handleChange}
            value={this.state.text />
        </form>
        <div>
          <TodoList items={this.state.items} />
        </div>
      </div>
    );
}

handleChange(e) {
    this.setState({ text: e.target.value });
}

handleSubmit(e) {
    e.preventDefault();
    if (!this.state.text.length) {
        return;
    }
    const newItem = {
       text: this.state.text,

    };
    this.setState(prevState => ({
      items: prevState.items.concat(newItem),
      text: ''
    }));
}
}

class TodoList extends React.Component {
    render() {
       return (

         <div>

          {this.props.items.map(item => (
           <h3 key={item.id}>{item.text}</h3>
          ))}

         </div>  
       );
    }

}

Answer №1

Your code will always generate an <h3> tag even if the input contains whitespace.

The appearance of a horizontal line is likely due to the CSS styles assigned to the h3 elements.

To prevent users from entering whitespace data, one solution is to use the trim() method to remove leading and trailing white spaces before checking the length:

// In handleSubmit()
if (!this.state.text.trim().length) {
  return;
}

By implementing this, any input containing only whitespace will be converted to a zero length string and exit the handleSubmit() function early.


import React, { Component } from 'react'

class TodoList extends React.Component {
  render() {
    return (
      <div>
        { this.props.items.map(item => <h3 key={ item.id }>{ item.text }</h3>) }
      </div>
    );
  }
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { items: [], text: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({ text: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();
    if (!this.state.text.trim().length) {
      return;
    }
    const newItem = {
      text: this.state.text,

    };
    this.setState(prevState => ({
      items: prevState.items.concat(newItem),
      text: ''
    }));
  }

  render() {
    return (
      <div>
        <form onSubmit={ this.handleSubmit }>
          <input onChange={ this.handleChange } value={ this.state.text }/>
        </form>
        <div>
          <TodoList items={ this.state.items } />
        </div>
      </div>
    )
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Repeating SignalR Messages: Issue of Duplication when Stopping and Restarting

Whenever I stop and start the connection, messages sent to the client by the hub are duplicated. If I follow this sequence: $.connection.hub.stop() $.connection.hub.start() {...} and a message is sent from the server hub to the client, it is initially re ...

Encountering a difficulty in sending data to the server through ajax with Cordova

I am currently working on a Phonegap Cordova project and I'm trying to send data to the server using AJAX but I'm encountering an error. Here is an example of my code: $(document).ready(function() { $('#frm').submit(function() ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

The element selector for the <code> tag is not recognized in SCSS

Update on 2020/02/23: I have made some additions to my project. Apologies for the lack of information provided earlier. The project I am working on is a modified version of the [Gatsby + Netlify CMS Starter][1]. In the process, I swapped out all.sass wit ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

"Steps to retrieve the button's ID when using the onClick event in Reactjs

Currently, I am working with Reactjs and Nextjs. I am utilizing functional components instead of classes. Within a loop, I have buttons and I am attempting to retrieve the id of the button when clicked using "onClick". Unfortunately, I am encountering th ...

React application encounters compilation errors following the installation of Express and Cors

I've been working on a React application that's designed to fetch an mp3 file from a server, but I keep encountering a CORS error. In an attempt to resolve this issue, I followed a suggestion to enable CORS by installing express and cors using np ...

Issue with displaying Cloudinary image

After uploading my image to Cloudinary and getting the URL, I attempted to display it in React. Here is the URL: . Unfortunately, the image did not show up as expected. You can find my codesandbox with the issue here: https://codesandbox.io/s/cool-christ ...

Exploration of narrowing union types in React with TypeScript

import { Chip } from "@mui/material"; type CourseFilterChipsRangeType = { labels: { from: string; to: string }; values: { from: number; to: number }; toggler: (from: number, to: number) => void; }; type CourseFilterChipsCheckType = { ...

Using jquery to refresh several backgrounds at once

While I have some knowledge of CSS and various JavaScript libraries, I've encountered difficulty in integrating multiple backgrounds into the code that I found on this link: http://codepen.io/quasimondo/pen/lDdrF. My goal was to overlay a transparent ...

Receiving the [object HTMLInputElement] on the screen rather than a numerical value

I have an input box where a user can enter a number. When they click a button, I want that number to be displayed on the page. However, instead of seeing the number, I am getting the output as [object HTMLInputElement]. Below is my TypeScript code: let qu ...

Ways to determine if your code is written in ES6

After completing a lot of Javascript coding, I just learned about the existence of various JS 'versions' such as ES5 and ES6. My project is now up on Github, and someone advised me to convert my ES6 code to ES5 using Babel. The problem is, I&ap ...

Inconsistent rendering issue identified in AngularJS when updating arrays with ui-router

I'm leveraging ui-router to navigate to specific subpages in my application: var myApp = angular.module("myApp",['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('usergroups&apos ...

Concealing objects identified by a specific id

I have two separate div elements var promptContent = $('<div id="errorr">').addClass("formErrorContent").html(promptText).appendTo(prompt); var arrow = $('<div id="errorrarrow">').addClass("formErrorArrow"); I need to refe ...

HTML button failing to connect with CSS stylesheet

I am currently teaching myself CSS and using W3schools for guidance. Recently, I added a button to my website that redirects users to another page upon clicking. Everything functions correctly, but now I want to style the button using CSS. However, despit ...

steps for setting up socket.io client

Would it be possible to reference the socket.io client library using a relative path like: src="/socket.io/socket.io.js" instead of the absolute path: src="https://miweb:6969/socket.io/socket.io.js" To establish a connection with the library, typically ...

Incorporate JSON data into a subsequent AJAX call when coding in JavaScript

I am facing an issue where I need to use data returned from an ajax request to construct a string and then post it back using ajax. However, the variable I'm assigning the data to is not within the scope of the second request, resulting in a 'var ...

What is the process of generating a row in AngularJS?

I am struggling to create a row as shown in the image. Currently, my circle is not positioned on the right side and my "P" element is not receiving the background color. Here is the code snippet: http://plnkr.co/edit/qIz2rFgW8n3J92evCRTd?p=preview Is it p ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

Firestore implementing batching for realtime updates with the onSnapshot 'IN' condition

Summary I'm currently working on developing a Chat List feature similar to those found in major social networks. However, I'm facing challenges with managing state in React Native due to a common issue with Firestore involving the use of onSnaps ...