Home > front end >  How to add text dynamic in defaultValue property with TextField from MUI
How to add text dynamic in defaultValue property with TextField from MUI

Time:10-07

I'd like to add Edited text after the message if the edit value is true.

How can I do that with TextField component from MUI?

import React, { useState } from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";

export default function BasicTextFields() {
  const [edit, setEdit] = useState(true);

  const comment = "This is a comment from user.";
  const message = `${comment} ${edit ? "Edited" : null}`;

  return (
    <Box component="form" noValidate autoComplete="off">
      <TextField
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        defaultValue={message}
        style={{ width: "300px" }}
      />
    </Box>
  );
}

Currently, I'm seeing This is a comment from user. Edited text when the edit is true and This is a comment from user. null text when the edit is false.

I just want to display Edited and don't need to show null.

Attempts

I tired

const message = `${comment} ${edit && "Edited"}`;

but this shows This is a comment from user. false text in the text input.

CodePudding user response:

The null is being transformed into a string. Try instead:

const message = ${comment} ${edit ? "Edited" :""};

  • Related