Building Reusable Split Screen Layouts in React
Annamalai Palani
Senior Product Developer at Lumel | React, Redux, D3, Node, JavaScript | Open-source contributor | Frontend
Split screen layouts are commonly used in web applications to display content side by side. Whether it's comparing two pieces of information or simply organizing content more efficiently, split screen layouts can improve the user experience.
Basic Split Screen Component
Let's begin by creating a basic version of the SplitScreen component:
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
display: flex;
`;
const Panel = styled.div`
flex: ${props => props.flex};
`;
const SplitScreen = ({ Left, Right }) => {
return (
<Container>
<Panel flex={1}>
{Left}
</Panel>
<Panel flex={1}>
{Right}
</Panel>
</Container>
);
};
export default SplitScreen;
In this component:
Enhanced Split Screen Component
Now, let's enhance our SplitScreen component to make it more flexible by allowing custom widths for the left and right sections:
import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
display: flex;
`;
const Panel = styled.div`
flex: ${props => props.flex};
`;
const SplitScreen = ({ children, leftWidth, rightWidth }) => {
const [left, right] = children;
return (
<Container>
<Panel flex={leftWidth}>
{left}
</Panel>
<Panel flex={rightWidth}>
{right}
</Panel>
</Container>
);
};
export default SplitScreen;
In this enhanced version:
领英推荐
Example Usage
Now, let's see how we can use our SplitScreen component in a React application:
import React from 'react';
import SplitScreen from './SplitScreen';
const LeftComponent = ({ title }) => {
return <h2>{title}</h2>;
};
const RightComponent = ({ title }) => {
return <h2>{title}</h2>;
};
function App() {
return (
<SplitScreen leftWidth={1} rightWidth={3}>
<LeftComponent title={"Left"} />
<RightComponent title={"Right"} />
</SplitScreen>
);
}
export default App;
In this example:
By following this approach, you can easily incorporate split screen layouts into your React applications, making them more structured and user-friendly. Feel free to customize the component further to suit your specific needs and styling preferences. Always expecting your support and suggestions ! Thanks in advance
Full-Stack Developer | MERN, Django, and Flutter Expert | SQL/NoSQL Hybrid, Cloud & Automation Enthusiast
1 年Very useful, will try