Lloyd Rajoo
Lloyd Rajoo

Reputation: 147

My required and defaultValue attributes are not working on my Textfield, but placeholder is

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}
    />
  )}

Upvotes: 1

Views: 439

Answers (1)

Soroush Salehi 404
Soroush Salehi 404

Reputation: 323

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

Upvotes: 1

Related Questions