Home > Enterprise >  How to check if component returns false in react?
How to check if component returns false in react?

Time:04-06

I have the following code which I'm trying to refactor

const [edit, setEdit] = useState(false);
<ListItemText
        primary={edit ? 
            <TextareaAutosize ... />
           : <Typography ..../>}
      />

The TextareaAutosize repeats a lot through the app so I thought I would convert it into a separate component.

export default function Textarea(props) {
    const [edit, setEdit] = useState(false);
    if(edit){
        return(
            <TextareaAutosize .../>
        )
    }
    return false
}

As you can see, if edit is false the component returns false. The back at the top I thought I would do this

import Textarea from "../Textarea";
<ListItemText
        primary={Textarea ? 
            <Textarea ... />
           : <Typography ..../>}
      />

By my logic, there should be a way to check if component Textarea will return false, right?

CodePudding user response:

A "component" (JSX) is a UI element. You must return JSX or null, and the rendering engine will render the returned JSX or nothing if null.

You can check a flag and short-circuit:

{isFlag && <MyComponent ... />}

or have the component render or not (or if you want to keep state just show/hide):

<MyComponent isVisible={isFlag} />

Or possible return different components depending on flags:

if (isLoading) {
  return <MyLoadingSkeletonComponent />
}
<MyMainUIComponent />

EDIT: You may want to refactor into a compound component where you take the flag and hide the show/hide logic within it

const TextArea = ({edit, editMode, viewMode}) => (
  edit ? editMode : viewMode
)

// Call it with the flag and both components:

<TextArea
   edit={edit}
   editMode={<TextareaAutosize ... />}
   viewMode={<Typography ... />}
/>

CodePudding user response:

Have the best of the two worlds, your idea of refactoring is correct, but it is missing something.

try something like this:

export default function Textarea(props) {
  props.edit ? <TextareaAutosize .../> : <Typography ..../>
}

and

<ListItemText
        primary=<TextareaAutosize {edit} ... />
      />

In this case you have one place to change TextareaAutosize and Typography codes, less messy code in parent listing.

Hope this helps.

  • Related