Reputation: 4284
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
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
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
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