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

Encountering a Typescript Type error when attempting to include a new custom property 'tab' within the 'Typography' component in a Material UI theme

Currently, I am encountering a Typescript Type error when attempting to add a custom new property called 'tab' inside 'Typography' in my Material UI Theme. The error message states: Property 'tab' does not exist on type &apos ...

The function of adding data to a list in AngularJS seems to be malfunctioning

I have a JSON list that I am storing in an AngularJS variable called score $scope.jobTemplate = [{ type: "AddInstructions", visible: false, buttonText: "Add Instructions", editableInstructionsList: [{ Number: totalEditableInstruction, Text: "Instruction ...

Setting up breakpoints for nested rows in Bootstrap can be achieved by utilizing the responsive

Currently, I am in the process of learning how to create a responsive website. One thing that has me puzzled is how to set the breakpoints for the content when the screen size changes. Here is what I am aiming to achieve: https://i.sstatic.net/DeyD0.png ...

How to Keep MUI Draggable Dialog Within Screen Boundaries in React

Currently, I am utilizing the MUI library and focusing on the Draggable Dialog component available here. My main inquiry revolves around how to restrict the dialog from being dragged beyond the screen boundaries. Even after attempting to implement the fo ...

Building a custom login page with axios in a react-redux application

I've encountered an issue with my login page. When I click the submit button, it does not redirect to the main Dashboard page. Check out the code below for authentication/login.js: import React, { Component } from 'react' import { Field, ...

What is the proper way to transfer data to PHP using AJAX?

I'm facing an issue while trying to send FormData to a PHP file. When I press submit, nothing happens. However, when I send data separately, it works fine. <form method="post" class="code_form" enctype="multipart/form-data& ...

Having trouble generating an array for checkboxes using jQuery, AJAX, and PHP

I'm almost there, but there's something missing. I'm attempting to send variables from multiple checkboxes to a PHP page using jQuery. This is my code: <div id="students"> <div class="field"> <label> ...

The CSS-styled button I created is designed to display a list and has the functionality of submitting

Whenever I click on a button, it's supposed to show a list of choices. But instead, it tries to submit the values in the text input field. Css .dropbtn { background-color: #3498DB; color: white; padding: 16px; font-size: 16px; border: none; cursor ...

Comparing OLOO and OO in ReactJS for front-end web development

After reading Kyle's book, I found it to be extremely informative. However, I am a bit perplexed by the discussion in "You Don't Know JS: this & Object Prototypes". The series argues that the "Object Linking to Other Object" design pattern is cl ...

Ruby application requires refreshing for Ajax deletions to take effect

I am currently working on developing a task management app using Rails. Each to-do list in the app contains multiple tasks, and my issue lies in deleting a completed task with Ajax without having to manually refresh the page for it to vanish. As I am still ...

Is there a way to break this down so that I can obtain an array containing the data for each month?

My JSON structure is as follows: "meterConsumption": [ { "month": 1, "details": [ { "timestamp": "2020-01-01", ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

Is it truly necessary to remove packages from devDependencies to improve performance?

It is a common understanding that packages listed under devDependencies are typically not included in the final build. So why do we remove them for the sake of performance optimization? For instance, there are discussions about replacing Moment.js with a ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Firefox is unable to display SWF files

My code snippet: <div id="sw" style="cursor:pointer" > <object id="swfobj" type="application/x-shockwave-flash"> </object> The JavaScript part: function openfile(filePath) { $("#swfobj").attr("data", filePath); $("#sw ...

Utilizing ID for Data Filtering

[ { "acronym": "VMF", "defaultValue": "Video & Audio Management Function", "description": "This is defined as the Video and/or Audio Management functionality that can be performed on a Digital Item. The Video & Audio M ...

The expected result of getInitialProps() is an object, however it returned "undefined" instead

Currently, I am facing an issue where I am attempting to retrieve data from Firebase in my Next.js application using getInitialProps. However, while the data displays in the VS Code terminal along with some errors, when viewing in the browser, a message ap ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...