skip to Main Content

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

Answers


  1. Like this:

    function MyInput() {
      const MyFn = () => {
        return (
          <TextField
            autoFocus
            margin="dense"
            id="input"
            type="text"
            fullWidth
            variant="standard"
            value="abcd"
          />
        );
      };
    
      return (
        <span>
          <MyFn />
        </span>
      );
    }
    
    Login or Signup to reply.
  2. 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"
        />
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search