Hello and welcome to my new article on React. Today we are going to see how we can create a fragment with React.
A fragment is an area on the screen that changes when we press a button or a menu.
To create this fragment, first, we are going to create the menu that allows changing the screen:
We call it menu.tsx
import React, { useState, useEffect } from 'react'; export enum SectionMenu{ Home = 'Home', Data = 'Data', } interface Props { setContent: React.Dispatch<React.SetStateAction>; content: SectionMenu; } const Menu: React.FC = ({ setContent, content }) => { const handleButtonClick = (newContent: SectionMenu) => { setContent(newContent); }; const [hasOverflow, setHasOverflow] = useState(false); useEffect(() => { const handleResize = () => { const element = document.getElementById('menu-dashboard-container'); if (element) { setHasOverflow(element.scrollWidth > element.clientWidth); } }; window.addEventListener('resize', handleResize); handleResize(); return () => { window.removeEventListener('resize', handleResize); }; }, []); const menuItems = [ { label: 'Home', section: SectionMenu.Home }, { label: 'Data', section: SectionMenu.Data }, // Add more elements as needed ]; return (
); }; export default Menu;
This component looks like this:
You should modify the colors and elements that create the menu.
Now let’s create a screen that will contain the fragment that will change the content depending on what is clicked:
fragment.tsx
import React, { useState } from 'react'; import Menu, { SectionMenu } from './menu'; const DashboardScreen: React.FC = () => { const [content, setContent] = useState(SectionMenu.Home); const renderContent = () => { switch (content) { case SectionMenu.Home: return
Home Content
; case SectionMenu.Data: return
Data Content
; // Add more cases as needed default: return null; } }; return (
{renderContent()}
); }; export default DashboardScreen;
Now that we have the two components together, we can see how it changes sections when clicking on the bottom element without having to reload the entire page.