Sometimes, when building a React app, you might want to display text in a two-column or multiple columns layout to make it easier to read. Instead of manually splitting the text, you can use CSS Grid to dynamically adjust the number of columns based on the screen size. In this tutorial, we'll create a simple React component that does just that!
🚀 Let's start by making a TwoColumnDisplay
component. This component will take a block of text, split it into lines, and arrange them in columns.
jsximport styled from 'styled-components'; const Container = styled.div` display: grid; gap: 16px; grid-template-columns: repeat(${(props) => props.$sm}, 1fr); @media (min-width: 768px) { grid-template-columns: repeat(${(props) => props.$md}, 1fr); } @media (min-width: 1024px) { grid-template-columns: repeat(${(props) => props.$lg}, 1fr); } `; const TwoColumnDisplay = ({ text, sm = 2, md = 2, lg = 3 }) => { if (!text) return null; const lines = text.trim().split("\n"); return ( <Container $sm={sm} $md={md} $lg={lg}> {lines.map((line, index) => ( <div key={index}>{line}</div> ))} </Container> ); }; export default TwoColumnDisplay;
📌Ensure you have styled-components
installed in your project
shellnpm install styled-components
🎯Now, let's use our TwoColumnDisplay
component in a React app:
jsxconst text = `Line 1\nLine 2\nLine 3\nLine 4`; <TwoColumnDisplay text={text} sm={1} md={2} lg={2} />;