When experimenting with styled components in my application, I encountered an issue where the cursor would unexpectedly move out after entering a city name

Whenever I input a letter in the search bar, the cursor automatically moves out and I have to click back into the text area to continue typing. This issue only occurs when using Styled components, as CSS works fine in this regard. It seems like there might be a problem with my styling but I can't seem to debug it successfully. Can someone provide assistance on how to resolve this issue?

import React, { FC, useState, FormEvent } from 'react';
import { useDispatch } from 'react-redux';
import styled from 'styled-components';
import { setAlert } from '../store/actions/alertActions';
import { getWeather, setLoading } from '../store/actions/weatherActions';

interface SearchProps {
  title: string;
}


const Search: FC<SearchProps> = ({ title }) => {
  const dispatch = useDispatch();
  const [city, setCity] = useState('');

  const changeHandler = (e: FormEvent<HTMLInputElement>) => {
    setCity(e.currentTarget.value);
  }

  const submitHandler = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if(city.trim() === '') {
      return dispatch(setAlert('City is required!'));
    }

    dispatch(setLoading());
    dispatch(getWeather(city));
    setCity('');
  }
   
  const Header = styled.h1`
    font-size: 40px;
    font-family:  'sans-serif';
    padding-top: 30px;
  `;

  const Input = styled.input`
    font-size: 18px;
    padding: 10px;
    margin: 10px;
    background: #b4e6df;
    border: none;
    border-radius: 3px;
    ::placeholder {
      color: black;
      
    }
  `;

  const Button = styled.button`
    background-color: #10e2f1;
    font-size: 20px;
    color: white;
    margin: 1em;
    border: 3px;
    padding: 0.25em 6em;
    
  `;
  return(
    <>
          <Header >{title}
          <form  onSubmit={submitHandler}>
            <Input 
              type="text"
              placeholder="Enter city name"
              value={city}
              onChange={changeHandler}
            />
            <br/>
            <Button >Search</Button>
          </form>
          </Header>
    </>
  );  
}

export default Search;

Answer №1

It seems like the value is dynamically updating whenever there is a change in the input field because it is connected to the state and the state gets updated on the onChange event. To maintain an independent value, you should use a separate variable instead of directly using the state variable in the value attribute. Here's how you can do it:

const defaultCity = ''; // or any default value received from props
const [city, setCity] = useState(defaultCity);

---
---
<Input 
    type="text"
    placeholder="Enter city name"
    value={defaultCity}
    onChange={handleInputChange}
/>

Please test this solution and let me know if it resolves the issue.

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

Avoid rendering the React component until the AJAX call has completed

Suppose the following code is given: componentDidMount() { $.ajax({ type: 'GET', url: '/data/', dataType: 'text', success: function(response) { this.setState({data: response}) ...

Ensure that the Submit button remains disabled until the validation process is successfully completed

In my React application, I have implemented a validation schema using Yup for certain fields that require mandatory and regex checks. Would it be feasible to have the Submit button disabled on the form until the Yup validation schema is successfully passe ...

Checking for grammar and spelling errors using Node.js

How can I incorporate spell checking, grammar and punctuation error detection, greeting usage, short keyword analysis, and time tracking for each chat session in my socket.io express mongoose chat application? Although I have successfully implemented a sp ...

Applying different styling to the same class within a different element using the + selector

Have you ever come across a website with code similar to what I've shared on this jsfiddle: https://jsfiddle.net/roa8k7js/ This particular site boasts an elaborate CSS styling sheet, exceeding 10,000 lines in length. When transitioning this website t ...

arranging texts in a vertical stack with wrapping

Looking to change the orientation of my horizontally wrapped list items from vertical to horizontal. Take a look at my code snippet: HTML <ul> <li>Long text goes here.</li> <li>Another Longer Text Goes Here</li> < ...

The animation for collapsing a flex-column navigation is appearing oddly strange

I'm currently working on creating a sidebar navigation using the Bootstrap 4 framework. The menu should be displayed at the top of the page on small devices. Here is my approach: .sidebar { background-image: linear-gradient(180deg, rgb(33, 243, ...

React Native throws an error when trying to convert a JSON value of type NSNULL, which is '<null>', to a valid URL

Currently, I am working on an app that requires me to access the device photo gallery in order to replace a default image displayed on the screen. The default value is set to null, which seems to work fine on Android but throws an error on iPhone devices. ...

Tips for resolving the error message "TypeError: props.scoreboard.map is not a function" that only occurs after refreshing the page

I'm encountering an unusual problem while attempting to iterate over the response from my backend. Despite logging the response as an array, I still face issues similar to those where the response is not considered an array. I am passing the scoreboa ...

What could be the reason that the Negator pseudo-class fails to function properly in jQuery?

Here is the code snippet I've been working on. It should be self-explanatory. $('body:not(#name)').click(function () { if (document.getElementById('name').value === '') { document.getEl ...

Applying ng-class based on conditions to icons within table cells

In my table, I am using ng-repeat to bind cells with data. One cell contains edit, save, and delete icons. When an order is posted, the delete/save icons should be disabled and displayed in a different color. While I can disable the click event of the icon ...

Encountering a syntax error while attempting to call a function using react.js Ref

x Expected ',', got '.' ,-[E:\projects\Coding Stuff\MyThing\thingymajig\src\pages\MainMenu.js:13:1] 13 | 14 | 15 | function BeginTransaction( 16 | inputRef.c ...

How to Create a DataTable Responsive Feature Where All Columns Collapse on Click, Except the Last One?

I am currently utilizing the DataTables library to generate a responsive table. I am aiming to create a feature where all columns in the DataTable can toggle between collapse and expand states when clicked, with the exception of the last column. Below is a ...

Troubleshooting a Responsive DIV with Hover Effects in CSS

I am encountering an issue with the mobile version of a responsive website that I am constructing. The green "info" DIV seen at the top left corner in the full-screen version needs to be relocated and placed at the bottom of the screen, just above the foo ...

Execute a single command to launch both the test and application simultaneously

I currently have the following two script commands defined under package.json: "dev": "react-scripts start", "test": "react-scripts test", Is there a method to execute both of these commands using just one command? ...

Is it possible for media queries to effectively support mobile devices?

I have a specific requirement for my <input type="number"> element where I need the up and down spinner buttons to be displayed for selecting the next value. However, on mobile devices, these spinner buttons are not visible. To address this ...

Hide the scrollbar when scrolling is unnecessary

After applying the CSS below, a div I have now has a scrollbar. The issue is that even when scrolling isn't necessary, the bar still appears empty. Is there a method to only display the scrollbar if the content overflows? Any suggestions would be appr ...

Incorporate Google Charts into your ReactJS application for dynamic data visualization

I am working on integrating Google Charts into a ReactJS application without using "react-google-chart". However, I encountered an error in the console stating that 'google is not defined'. Below is my current code snippet: In my index.html: ...

Round Modal Design using Bootstrap

I have successfully created a circular form bootstrap modal, but I am struggling with how to insert text in the center of the circle responsively. Can anyone help? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/boots ...

Prevent duplicate items in an array by utilizing the Map object to add elements

Looking for a way to update an array by adding new values while avoiding duplicates. I've implemented the usage of a Map object to keep track of existing values and tried filtering the new array accordingly. const [items, setItems] = useState([]); ...

I find the Accordion is almost ready once I make some edits

When attempting to edit the playlist name, I notice that the accordion closes. Also, when my mouse hovers over the input field for the playlist name and I press the spacebar on the keyboard, the top playlist moves down while the bottom one moves up. Why is ...