1

I have a simple edit functionality on the card below.

When I click edit, a textfield should appear that allows me to save it.

However, the required and defaultValue attributes are not working on my Textfield, but placeholder is (see image Textfield Issue).

Saving the edited text isn't a problem (haven't included that code here), just the aspects above.

Any help is much appreciated!!

<Card
  style={{
    backgroundColor: `${
      task.isComplete ? "lightgreen" : task.priority ? "lightcyan" : ""
    }`
  }}
>
  {taskEditing === task.id ? (
    <CardHeader
      action={
        <IconButton aria-label="SaveEdits">
          <SaveIcon onClick={() => editTask(task.id)} />
        </IconButton>
      }
      title={
        <TextField
          style={{ width: 410 }}
          required
          variant="outlined"
          onChange={(e) => setEditingText(e.target.value)}
          defaultValue='hello'
          placeholder='This is a placeholder'
          value={editingText}
        />
      }
    />
  ) : (
    <CardHeader
      action={
        <IconButton aria-label="Edit">
          <EditIcon onClick={() => setTaskEditing(task.id)} />
        </IconButton>
      }
      title={task.text}
    />
  )}
Lloyd Rajoo
  • 137
  • 2
  • 13
  • Sorry, I realized this is a controlled field so I can't use default value. I'd like to get the previous value of the field instead - can anyone help me do that? – Lloyd Rajoo Sep 14 '21 at 11:34
  • Got an answer separately - I'm meant to use the UseRef hook - see this question https://stackoverflow.com/questions/69177050/how-do-i-get-the-previous-value-of-a-field-in-react-i-want-to-use-it-to-display – Lloyd Rajoo Sep 14 '21 at 12:37

1 Answers1

1

for the required if you set the label property, the * shown in TextField, and for defaultValue if editingText equal empty string like "" TextField show placeholder and when editingText equal null TextField show your default value. its look like this:

....
const [editingText, setEditingText] = React.useState(null);
...
 <TextField
        required
        label="text"
        variant="outlined"
        onChange={(e) => setEditingText(e.target.value)}
        defaultValue="hello"
        placeholder="This is a placeholder"
        value={editingText}
  />

here is codesandbox