Missing TextField

67 Views Asked by At

OK, so I have another issue which is driving me bonkers.

This works (ie I see a TextField on the glass):

import TextField from '@mui/material/TextField';

function MyInput() {
  
  return (
    <span>
        <TextField
          autoFocus
          margin="dense"
          id="input"
          type="text"
          fullWidth
          variant="standard"
          value="abcd"
        />
    </span>
  )
}
   
export default MyInput;

This doesn't (ie no TextField is displayed: the DOM contains <div class="MuiFormControl....." which in turn contains the elements, but nothing in between them).)

import TextField from '@mui/material/TextField';

function MyInput() {

  const myfn = () => {
    return
        <TextField
          autoFocus
          margin="dense"
          id="input"
          type="text"
          fullWidth
          variant="standard"
          value="abcd"
        />
  }

  return (
    <span>
      {myfn()}
    </span>
  )
}

export default MyInput;

Any ideas as to why the second implementation doesn't display a text input field will be gratefully received!

2

There are 2 best solutions below

1
Sayid On BEST ANSWER

If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.

Like this:

function MyInput() {
  const MyFn = () => {
    return (
      <TextField
        autoFocus
        margin="dense"
        id="input"
        type="text"
        fullWidth
        variant="standard"
        value="abcd"
      />
    );
  };

  return (
    <span>
      <MyFn />
    </span>
  );
}
1
Akeel Ahmed Qureshi On

The return statement in 'myfn' has a line break right after the 'return' keyword and because of the line break, the function returns undefined and the JSX code for the 'TextField' is never reached.

You should either remove the line break or use parentheses to wrap the JSX:

  const myfn = () => {
  return <TextField
    autoFocus
    margin="dense"
    id="input"
    type="text"
    fullWidth
    variant="standard"
    value="abcd"
  />
}

Wrap JSX in parentheses like this:-

const myfn = () => {
  return (
    <TextField
      autoFocus
      margin="dense"
      id="input"
      type="text"
      fullWidth
      variant="standard"
      value="abcd"
    />
  );
}