Home > front end >  Can I pass JSX to value property with TextField component from MUI?
Can I pass JSX to value property with TextField component from MUI?

Time:10-11

Can I pass JSX/html to the value property with TextField component from MUI?

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

export default function BasicTextFields() {
  const message = "Hello World";
  const [commentText, setCommentText] = useState(message);
  const comment = { editedText: true };

  const messageEdited = `${commentText}${
    comment.editedText ? " (Edited)" : ""
  }`;

  return (
    <Box component="form" noValidate autoComplete="off">
      <TextField
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        value={messageEdited}
      />
    </Box>
  );
}

Instead of having messageEdited like this

  const messageEdited = `${commentText}${
    comment.editedText ? " (Edited)" : ""
  }`;

Can I do something like this?

  const messageEdited = () => {
    return (
      <>
        <div>commentText</div>
        <span>(edited)</span>
      </>
    );
  };

  return (
    <Box component="form" noValidate autoComplete="off">
      <TextField
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        value={messageEdited()}
      />
    </Box>
  );
}

Passing the messageEdited function to the value property displays [object Object] inside the text input.

The doc says the value property takes any so wonder if I can do it. https://mui.com/material-ui/api/text-field/

Attempts

  const renderMessage = () => {
    return [
      <div key={comment._id}>{comment.text}</div>,
      <span key={comment._id}>(edited)</span>,
    ];
  };

  return (
    <Box component="form" noValidate autoComplete="off">
      <TextField
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        value={messageEdited()}
      />
    </Box>
  );
}

CodePudding user response:

I looked at the source code and:

  1. value is passed down to Input here
  2. down to InputBase here
  3. and to input element here

input element automatically converts everything to string, so maybe this component can take anything, but in normal text input mode it will always return everything to string

CodePudding user response:

No, if you do it you will get an error

Invalid value for prop `value` on <input> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior 

What are you trying to accomplish?

  • Related