Reputation: 171
I am trying to get my hands on compound component pattern in ReactJS. And all is good but I am not able to export the component the way I want.
I have created one basic Table (Data Grid), which has many component like header, row, column, search, pagination etc.
And I want the end user to import this Table in this way.
import Table from './Table'
const DataGrid = () => {
return (
<Table>
<Table.Title></Table.Title>
<Table.Header>
<Table.Row></Table.Row>
</Table.Header>
<Table.Body>
<Table.Row></Table.Row>
</Table.Body>
</Table>
)
}
Now in component folder, I have one index.js file where I am trying to import all component and then trying to export it in a object
import {Table} from './Table'
import {Title} from './Title'
import {Header} from './Header'
import {Body} from './Body'
Now what should I do to export in a way I want. Tried many solutions, but nothing is working.
Upvotes: 3
Views: 1469
Reputation: 19813
You need to import everything in index
file and prepare a new object and export it:
index.js:
import { Table } from "./Table"; // this imports from Table.jsx file
import { Title } from "./Title";
import { Body } from "./Body";
import { Header } from "./Header";
import { Row } from "./Row";
const all = Table; // <-- Here: this (all) is the new object.
// We can name it whatever we want as it is going to be a default export
all.Title = Title;
all.Body = Body;
all.Header = Header;
all.Row = Row;
export default all;
Now, you can use it like shown below:
DataGrid.jsx:
import Table from "./Table"; // this imports from index.js file under "Table" folder
const DataGrid = () => {
return (
<Table>
<Table.Title></Table.Title>
<Table.Header>
<Table.Row></Table.Row>
</Table.Header>
<Table.Body>
<Table.Row></Table.Row>
</Table.Body>
</Table>
);
};
This answer assumes that you have components under directories like below. Make sure to change the paths when importing if you have a different one.
src/
Table/
Body.jsx
Header.jsx
index.js
Row.jsx
Table.jsx
Title.jsx
DataGrid.jsx
Upvotes: 5