720 words
4 minutes
Rewriting a Component with ReactDOM.createPortal

I recently joined a project where one interaction convention is that search conditions stay hidden by default and are revealed by clicking a filter icon. My team came on later to build custom features on top of it, so we had to follow the same convention. Another developer had already shipped a component for this, but I felt its extensibility and maintainability were poor — so I decided to rewrite it with ReactDOM.createPortal.

Component Preview#

The Original Component#

Here’s how the existing component is used. As you can see, it takes two imports — FilterIcon and FilterView. FilterIcon is the filter button; its whole job is toggling the search panel on click.

FilterView defines the search conditions, which are abstracted out and passed in as searchList.

// example pseudocode
import FilterIcon from "@/pages/LuZhiBI/components/FilterIcon/filterIcon";
import FilterView from "@/pages/LuZhiBI/components/FilterView";
const searchList: any[] = [
{
searchType: "string",
searchComponentType: "input",
placeHolder: "Enter an indicator name",
title: "Indicator Name",
key: "indicatorName",
},
{
searchType: "string",
searchComponentType: "multipleSelect",
placeHolder: "Select an indicator type",
title: "Indicator Type",
key: "indicatorType",
options: options.classificationOfIndicatorsOptions,
mode: "multiple",
defaultValue: options.classificationOfIndicatorsOptions.map(item => item.value),
},
{
searchType: "text",
searchComponentType: "dateRangeTime",
showTime: true,
title: "Created At",
key: "createdAt",
},
];
<div className={styles.container}>
<div className={styles.headBox}>
...
<div className={styles.searchBox}>
...
<FilterIcon handleFilterClick={handleFilterClick} filterTitle="Filter" />
...
</div>
</div>
<FilterView ref={filterViewRef} searchList={searchList} finish={onFinish} defaultFormValue={defaultSearchInfo} />
</div>

A few shortcomings stand out:

  • One feature, yet two components have to be imported and coordinated
  • You have to grab a FilterView ref manually and drive show/hide through handleFilterClick
  • The searchList schema is convoluted and hostile to customization — every custom case means editing the original component and bolting business logic inside. As the project iterates, the component balloons and becomes hard to maintain (a previous project of mine fell into exactly this trap). On top of that, searchList comes with no TypeScript hints, which defeats the purpose of using it in a TS project.

The New Component#

Before writing the new component, I thought of Vue’s built-in Teleport, which renders elements from inside a component to a DOM node elsewhere in the document. That made me wonder whether React had an equivalent — and it does: ReactDOM.createPortal, which does essentially the same thing as Teleport.

How It Works#

ReactDOM.createPortal takes two arguments: the children to render, and the target DOM node.

For our needs the component has two parts: a fixed filter icon, and children that get teleported to a target location. Here’s the final implementation:

import { type FC, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { Button, Tooltip } from 'antd';
import { FilterOutlined } from '@ant-design/icons';
import { motion } from 'framer-motion';
interface IProps {
hoverTitle: string;
nodeID: string;
children?: React.ReactNode;
}
const FilterIcon: FC<IProps> = props => {
const { hoverTitle = 'Filter', nodeID, children } = props;
const [node, setNode] = useState<any>(null);
const [height, setHeight] = useState<string | number>(0);
const filterClick = () => {
if (height === 0) {
setHeight('auto');
} else {
setHeight(0);
}
};
useEffect(() => {
const targetNode = document.getElementById(nodeID);
setNode(targetNode);
}, [nodeID]);
return (
<>
<Tooltip placement="bottom" title={hoverTitle}>
<Button
onClick={filterClick}
icon={
<FilterOutlined
style={{
fontSize: 16,
}}
/>
}
type="text"
></Button>
</Tooltip>
{node &&
ReactDOM.createPortal(
<motion.div
animate={{ height }}
className="filter-conditions"
style={{
height: 0,
overflow: 'hidden',
width: '100%',
backgroundColor: '#f5f5f5',
borderRadius: 4,
marginTop: 10,
padding: '0 16px',
}}
>
{children}
</motion.div>,
node,
)}
</>
);
};
export default FilterIcon;

Usage#

Usage is simple: import Filter, drop an empty <div id="filter-main" /> wherever the panel should appear, and pass that id to the component. The filter conditions themselves go directly inside Filter as children.

// example pseudocode
import Filter from '@/pages/LuZhiBI/components/Filter';
<div className={styles.DatasetView}>
<div className={styles.titleBox}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div className={styles.filterBox}>
<Filter hoverTitle="Filter" nodeID="filter-main">
<Form
name="filter"
onFinish={onFinish}
autoComplete="off"
initialValues={{
date: [],
indicator: [''],
}}
>
<Row gutter={16} style={{ marginTop: 16 }}>
<Col span={8}>
<Form.Item<FieldType>
label="Date"
name="date"
rules={[{ required: true, message: 'Please select a query date' }]}
>
<RangePicker style={{ width: '100%' }} />
</Form.Item>
</Col>
<Col span={8}>
<Form.Item<FieldType>
label="Indicator"
name="indicator"
required
rules={[{
validator: (_rule, value) => {
if (!value && value !== '') {
return Promise.reject('Please select an indicator');
}
return Promise.resolve();
}
}]}
>
<Select mode='multiple' options={indicatorOptions} />
</Form.Item>
</Col>
<Col span={8}>
<Flex justify="flex-end">
<Form.Item>
<Space size="small">
<Button htmlType="reset">
Reset
</Button>
<Button type="primary" htmlType="submit">
Query
</Button>
</Space>
</Form.Item>
</Flex>
</Col>
</Row>
</Form>
</Filter>
</div>
</div>
<div id="filter-main" />
</div>
</div>
Rewriting a Component with ReactDOM.createPortal
https://www.mihouo.com/en/posts/front/rewriting-components-with-reactdomcreateportal/
Author
Jia
Published at
2024-07-17
License
CC BY-NC-SA 4.0