Phoenix
Phoenix

Reputation: 4284

using If/Else statement in ReactJs to return a component

Here is courseButton.jsx:

import React from "react";
import styles from "./styles.module.scss";
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";

export default (props) => {
  const { collapsed, onClick } = props;

  return <>{collapsed ? MenuUnfoldOutlined : MenuFoldOutlined}</>;
};

Both of my components have the same props. So I want to avoid coding like this:

import React from "react";
import styles from "./styles.module.scss";
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";

export default (props) => {
  const { collapsed, onClick } = props;

  return (
    <>
      {collapsed ? (
        <MenuUnfoldOutlined className={styles.trigger} onClick={onClick} />
      ) : (
        <MenuFoldOutlined className={styles.trigger} onClick={onClick} />
      )}
    </>
  );
};

So how I can give the selected component the style in one line code.

I want something like this code.

Upvotes: 2

Views: 320

Answers (3)

Dennis Vash
Dennis Vash

Reputation: 53934

This solution scales better as we assign props only once.

export default (props) => {
  const { collapsed, onClick } = props;
  const Component = collapsed ? MenuUnfoldOutlined : MenuFoldOutlined;
  return <Component className={styles.trigger} onClick={onClick} />;
};

Upvotes: 3

kind user
kind user

Reputation: 41893

If I understood you correctly, you want to keep your code DRY. You can store your props in a variable to keep it reusable.

export default (props) => {
    const {collapsed, onClick} = props;

    const genericProps = {
       className: styles.trigger,
       onClick,
    }

    if (collapsed) {
       return <MenuUnfoldOutlined {...genericProps} />
    }

    return <MenuFoldOutlined {...genericProps} />
}

Note: React Fragment is redundant.

Upvotes: 1

rzk666
rzk666

Reputation: 223

you can simply write it like this:

import React from "react"
import styles from "./styles.module.scss"
import {MenuFoldOutlined, MenuUnfoldOutlined} from '@ant-design/icons'


export default (props) => {
    const {collapsed, onClick} = props

    return (
        <>
            {collapsed ? <MenuUnfoldOutlined {...props} /> : <MenuFoldOutlined {...props}/>}
        </>
    )
}
  • This is the same as writing . If the wrapping component has a bunch of props and you only need specific props you can try the following approach:

    export default (props) => { // If props has a bunch of props but we only need collapsed and // onClick: const {collapsed, onClick} = props const menuProps = {collapsed, onClick}

        return (
            <>
                {collapsed ? <MenuUnfoldOutlined {...menuProps} /> : <MenuFoldOutlined {...menuProps}/>}
            </>
        )
    }
    

Upvotes: 0

Related Questions