'Multiple React Components in a Single JSX File Not Working in React 18 [duplicate]
I am trying to write multiple components in a single .jsx
file. But for some reason it doesn't work in React 18. It was working fine in the previous Versions. But when i create a separate .jsx
file for the component and import it, it works. Following is an example code:
const ChannelListContainer = () => {
return (
<>
<Sidebar logout={logout} />
<div className="channel-list__list__wrapper">
<CompanyHeader />
<ChannelSearch />
<ChannelList
filters={{}}
channelRenderFilterFn={() => {}}
List={(listProps) => <TeamChannelList {...listProps} type="team" />}
Preview={(previewProps) => (
<TeamChannelPreview {...previewProps} type="team" />
)}
/>
<ChannelList
filters={{}}
channelRenderFilterFn={() => {}}
List={(listProps) => (
<TeamChannelList {...listProps} type="messaging" />
)}
Preview={(previewProps) => (
<TeamChannelPreview {...previewProps} type="messaging" />
)}
/>
</div>
</>
);
};
The sidebar component imported in the above code was first meant to be in the same file. But i had to create the Sidebar component separately to use it. How can i write two components in the same .jsx
file and use them in React 18?
Solution 1:[1]
The issue was that it is now mandatory to add the return()
around the div
inside the component you want to render or else it won't render. This wasn't the case in the previous React versions. I might be wrong but this is currently the case for me. Note that both these components are in a single .jsx
file.
const Sidebar = ({ logout }) => {
return ( // without this, the component won't render. This isn't the case in < 18 React.
<div className="channel-list__sidebar">
<div className="channel-list__sidebar__icon1">
<div className="icon1__inner">
<img src={HospitalIcon} alt="Hospital" width="30" />
</div>
</div>
<div className="channel-list__sidebar__icon2">
<div className="icon1__inner" onClick={logout}>
<img src={LogoutIcon} alt="Logout" width="30" />
</div>
</div>
</div>
);
};
const ChannelListContainer = () => {
return (
<>
<Sidebar logout={logout} />
<div className="channel-list__list__wrapper">
<CompanyHeader />
<ChannelSearch />
<ChannelList
filters={{}}
channelRenderFilterFn={() => {}}
List={(listProps) => <TeamChannelList {...listProps} type="team" />}
Preview={(previewProps) => (
<TeamChannelPreview {...previewProps} type="team" />
)}
/>
<ChannelList
filters={{}}
channelRenderFilterFn={() => {}}
List={(listProps) => (
<TeamChannelList {...listProps} type="messaging" />
)}
Preview={(previewProps) => (
<TeamChannelPreview {...previewProps} type="messaging" />
)}
/>
</div>
</>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mushood Hanif |