The focus on TextField in Material UI + React gets lost when applying styles to a card

Is there a way to style my card so that it appears smaller without affecting the functionality of my TextField? Whenever I try to reduce the size of the Card component, the TextField loses focus and I have to keep clicking on it. How can I make the Card smaller while maintaining the TextField's functionality?

https://codesandbox.io/s/mutable-monad-dsvf8?file=/src/index.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import TextField from "@material-ui/core/TextField";
import CreateIcon from "@material-ui/icons/Create";
import Box from "@material-ui/core/Box";
import CardMedia from "@material-ui/core/CardMedia";
import MuiAlert from "@material-ui/lab/Alert";
import Snackbar from "@material-ui/core/Snackbar";
import { withStyles } from "@material-ui/core/styles";

const PetitionCard = () => {
  const StyledCard = withStyles({
    root: { height: 450, width: 350 }
  })(Card);

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [open, setOpen] = useState(false);
  const [petition, newPetition] = useState(false);

  const handleTitleChange = event => {
    setTitle(event.target.value);
  };

  const handleDescriptionChange = event => setDescription(event.target.value);

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }
  };

  const Alert = props => <MuiAlert elevation={6} variant="filled" {...props} />;

  const Message = (message, severity) => {
    return (
      <Snackbar open={!open} autoHideDuration={3000} onClose={handleClose}>
        <Alert severity={severity}>{message}</Alert>
      </Snackbar>
    );
  };

  const clearField = event => {
    setOpen(true);
    if (title.length > 0 && description.length > 0) {
      setTitle("");
      setDescription("");
      return (
        <Message
          open={open}
          message={"You have successfully created a petition!"}
          severity={"success"}
        />
      );
    } else {
      return (
        <Message
          message={"You have one more more fields missing"}
          severity={"error"}
        />
      );
    }
  };
  return (
    <StyledCard>
      <Box mt={1}>
        <Grid container justify="center">
          <TextField
            id="outlined-multiline-static"
            multiline
            rows={1}
            variant="outlined"
            placeholder="Title"
            value={title}
            onChange={handleTitleChange}
          />
        </Grid>
      </Box>

      <CardMedia title="Petition" style={{ height: 0, paddingTop: "40.25%" }} />

      <Box mt={1} justify="center">
        <Grid container justify="center">
          <TextField
            size="small"
            inputProps={{
              style: { fontSize: 15 }
            }}
            id="outlined-multiline-static"
            multiline
            rows={5}
            placeholder="Description"
            variant="outlined"
            value={description}
            onChange={handleDescriptionChange}
          />
        </Grid>
      </Box>

      <Box mt={1}>
        <Grid container justify="center">
          <Button onClick={clearField}>
            <CreateIcon />
            Create Petition!
          </Button>
        </Grid>
      </Box>
    </StyledCard>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <PetitionCard />
  </React.StrictMode>,
  rootElement
);

Answer №1

The issue lies in the continuous recreation of StyledCard whenever PetitionCard is rendered:

const PetitionCard = () => {

    const StyledCard = withStyles({
        root: { height: 450, width: 350 }
    })(Card);

    [...]
}

As a result, a new instance of TextField is generated with each render due to the changing container. The new TextField does not retain focus and remains unaware of its state from the previous render.

To address this issue, it is recommended to define StyledCard outside of the scope of PetitionCard:

const StyledCard = withStyles({
    root: { height: 450, width: 350 }
})(Card);

const PetitionCard = () => {

    [...]
}

https://codesandbox.io/s/muddy-dew-i23ty?fontsize=14&hidenavigation=1&theme=dark

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

Challenge with Updating React Components When Switching Themes

In my React application, I'm facing a challenge with theme switching. There are two themes available: Theme One and Theme Two. To dynamically load theme components, lazy loading has been implemented based on the selected theme. Each theme has its own ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

Combining objects in an array by a specific property

In my current project, I am working with an array of objects. Each object in this array contains both an amount and a value property. What I need to achieve is that if two or more objects have the same amount value, I want to combine their values into one ...

The class name feature on the Drawer component is malfunctioning

React and material-ui are my tools of choice, but I've hit a roadblock. I'm attempting to define some custom CSS behavior for the drawer component, using the className property as recommended. However, despite following the instructions, it' ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

Tips for customizing angular-material radio buttons

I attempted to modify the appearance of the radio button component using CSS in my code, but unfortunately, it does not seem to be effective. The default setup for this component places the button on the left and the label on the right. I am interested in ...

I am encountering an issue with the callback function not functioning properly when utilizing react-flutterwave-rave in test mode. What could

I have integrated Flutterwave as the payment system for my web application that I am currently developing using React. To facilitate this integration, I have utilized the react-flutterwave-rave package available on npm. The implementation is functioning ...

Combining AngularJS objects from dual HTTP requests

My goal is to combine two HTTP.get requests into one $scope in order to display the data in the same ng-repeat table. I am utilizing chained promises in my AngularJS application as shown below: AngularJS: function getContainer() { $http.get(" ...

Displaying object properties within another object obtained from an API request in a React component

Dealing with API data can be tricky, especially when there are nested objects involved. I've encountered an error message stating 'undefined is not an object (evaluating 'coin.description.en')', as the description property of the c ...

Is fs-extra the best tool for working with a .bundle file?

I am attempting to determine whether a specific folder in my project includes a .bundle file and, if it does, relocate it to another location. If the file is not found, I will use a default option instead. The problem I'm encountering is that I am una ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Transferring data from JavaScript to an HTML page

I'm currently developing a rock, paper, scissors game using HTML and JS. Here is the link to the complete code (CSS, JS, HTML): http://jsfiddle.net/fJw4R/. You can also view the game with images here: The functionality of the .math-module is working ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...

Having trouble with page reload when implementing Angular Ui Router in Html5 mode with AngularJS?

Within my Angular app, I have implemented Angular UI Router and made use of HTML5 mode to eliminate the "#" from my URLs by utilizing the $locationProvider in the configuration. angular.module('myApp', ['ui.router']) .config(function( ...

What are the key steps in evaluating a grid layout design?

I recently heard that some designs do not support grid system layouts like Bootstrap or Foundation. This has left me unsure about what elements to analyze in a design before starting work on it. I know Bootstrap uses a 12-column grid system, but I am unc ...

"Enhance Your XYChart with a Striking Background Image Using Amchart

let chart = am4core.create("chartdiv", am4charts.XYChart); chart.background.image = am4core.image("/static/img/bar-chart.png") I'm attempting to apply a background image to my chart in Amchart, but unfortunately it's not di ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

Issues with rendering images in the browser due to CSS inline-block layout are causing

I have encountered an issue with two divs that are set to 50% width and displayed inline-block. Each div contains an image. I expected both divs to stay on the same line, but sometimes the browser breaks the layout. Here is the HTML code snippet: <div ...

Having difficulty implementing word-break: break-word CSS feature for Chinese and Japanese texts

I am trying to use the CSS property word-break: break-word on an HTML label. While it works well with roman scripts like English, German, and French, I'm facing issues with languages such as Chinese, Japanese, and Korean. Is there a solution to make t ...