Home > Enterprise >  How to successfully return compiled JSX MUI end tags from within wrapper
How to successfully return compiled JSX MUI end tags from within wrapper

Time:10-29

I'm trying to return a little MUI JSX from a function, ..but the compiler does not like some of the element end tags.

It complains about the last '</Grid> and <br />' elements

const gridRowHeader = () => {
    return (
        <Grid item xs={3} ></Grid> 
            <Grid item xs={5} justifyContent="center" > 
                <h2 class='classes.ModalHeader'> 
                    {t(title)}</h2> 
            </Grid> 
            <Grid item xs={3}>
            </Grid>
            <Grid item xs={1} direction="row-reverse" > 
                 <CloseIcon onClick={closeModal} /> 
            </Grid> 
        </Grid>
        <br'/'><br />
     );
};

Updated and fixed:

enter image description here

CodePudding user response:

Actually your code is wrong, you are trying to return more than one component

Try this

    const gridRowHeader = () => {
        return (
          <>
            <Grid item xs={3} />
                <Grid item xs={5} justifyContent="center" > 
                    <h2 class='classes.ModalHeader'> 
                        {t(title)}</h2> 
                </Grid> 
                <Grid item xs={3}>
                </Grid>
                <Grid item xs={1} direction="row-reverse" > 
                     <CloseIcon onClick={closeModal} /> 
                </Grid> 
            </Grid>
            <br /><br />
        </> 
     );
}

Also when a const function does nothing but returning something, the code could be simplified to this:

const gridRowHeader = () => 
         (
          <>
            <Grid item xs={3} />
                <Grid item xs={5} justifyContent="center" > 
                    <h2 class='classes.ModalHeader'> 
                        {t(title)}</h2> 
                </Grid> 
                <Grid item xs={3}>
                </Grid>
                <Grid item xs={1} direction="row-reverse" > 
                     <CloseIcon onClick={closeModal} /> 
                </Grid> 
            </Grid>
            <br /><br />
        </> 
     );

This way your component will return only one item. <>...</> is a shorthand to React fragment (read more here). Instead of a fragment you could use a <div>, but fragments do not introduce any new node in the DOM.

CodePudding user response:

You have a few errors.

<h2 class='classes.ModalHeader'>

Should be

<h2 className='classes.ModalHeader'>

You should remove as you shouldn't use <br /> for styling

<br /><br />

Here is the updated code:

const gridRowHeader = () => {
  return (
    <Grid item xs={3}>
      <Grid item xs={5} justifyContent="center">
        <h2 className="classes.ModalHeader">{t(title)}</h2>
      </Grid>
      <Grid item xs={3}></Grid>
      <Grid item xs={1} direction="row-reverse">
        <CloseIcon onClick={closeModal} />
      </Grid>
    </Grid>
  );
};
  • Related