JavaScript and React course ยท Module 7: Styling and Animations
Component Frameworks - Building Galactic Interfaces with shadcn/ui, Material-UI, and Chakra UI
In this lesson7
On our journey through the cosmos of frontend technologies, component frameworks are like advanced space stations - ready, comprehensive structures that we can populate with our own logic and customize to our needs. In this module, we will explore three popular component frameworks: shadcn/ui, Material-UI, and Chakra UI, which let you create consistent, beautiful, and functional user interfaces.
Why Use Component Frameworks?
Imagine you need to build an advanced spaceship. You can either construct every part from scratch, or use ready-made, tested, and optimized components. Component frameworks give you that second option, offering:
- Ready UI components - buttons, forms, cards, modals, tables, and many more
- Consistent design - all elements fit together visually and functionally
- Accessibility - components are built with accessibility in mind for all users
- Time savings - you do not need to reinvent the wheel every time
- Easy maintenance - updates, bug fixes, and new features are delivered by the community
shadcn/ui - A Modern, Unconventional Approach to Component Libraries
What is shadcn/ui?
shadcn/ui is a unique approach to component libraries. Unlike traditional frameworks, shadcn/ui is not a library you install as a dependency. Instead, it is a collection of components that you copy directly into your project. This gives you full control over the code and the ability to modify components without restrictions.
Installing and Configuring shadcn/ui
To start your adventure with shadcn/ui, follow these steps:
# Initialize shadcn/ui in the project
npx shadcn-ui@latest initDuring initialization, you will answer a few questions about configuration (styles, colors, etc.). Then you can add selected components:
# Adding the button component
npx shadcn-ui@latest add button
# Adding other components
npx shadcn-ui@latest add card
npx shadcn-ui@latest add dialogExample Usage of shadcn/ui Components
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
function MissionControl() {
return (
<Card>
<CardHeader>
<CardTitle>Mission Control Panel</CardTitle>
<CardDescription>Manage your cosmic expedition</CardDescription>
</CardHeader>
<CardContent>
<p>System status: All systems are operating correctly</p>
</CardContent>
<CardFooter>
<Button variant="outline" className="mr-2">Cancel</Button>
<Button>Start mission</Button>
</CardFooter>
</Card>
);
}Advantages of shadcn/ui
- Full control - components are in your code, you can modify them freely
- No dependencies - no need to worry about version conflicts or update issues
- Minimalist design - modern, clean component look
- Easy customization - based on Tailwind CSS for easy appearance adjustment
- Dark mode support - built-in dark mode support
Material-UI - Google-Style Interfaces
What is Material-UI?
Material-UI (MUI) is a popular React component library implementing the Material Design principles created by Google. It is like building a spaceship according to proven NASA plans - you get an interface that is intuitive, consistent, and familiar to users worldwide.
Installing Material-UI
# Installing basic MUI packages
npm install @mui/material @emotion/react @emotion/styled
# Optionally, for icons
npm install @mui/icons-materialExample Usage of Material-UI
import { Button, Card, CardActions, CardContent, Typography } from '@mui/material';
import RocketLaunchIcon from '@mui/icons-material/RocketLaunch';
function SpaceMission() {
return (
<Card sx={{ maxWidth: 345, m: 2 }}>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
Mission to Mars
</Typography>
<Typography variant="body2" color="text.secondary">
Prepare for a cosmic adventure. The mission to Mars requires courage,
knowledge, and readiness for the unknown.
</Typography>
</CardContent>
<CardActions>
<Button size="small" color="primary">Details</Button>
<Button
size="small"
variant="contained"
color="primary"
startIcon={<RocketLaunchIcon />}
>
Start
</Button>
</CardActions>
</Card>
);
}Theming in Material-UI
Material-UI offers an advanced theming system that lets you customize colors, typography, border radius, and many other aspects:
import { createTheme, ThemeProvider } from '@mui/material/styles';
// Creating a custom theme
const theme = createTheme({
palette: {
primary: {
main: '#2196f3', // cosmic blue
},
secondary: {
main: '#f50057', // stellar pink
},
},
typography: {
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
h1: {
fontSize: '2.5rem',
fontWeight: 500,
},
},
shape: {
borderRadius: 8,
},
});
// Applying the theme
function App() {
return (
<ThemeProvider theme={theme}>
{/* Place your components here */}
</ThemeProvider>
);
}Advantages of Material-UI
- Rich component library - from simple buttons to advanced table components
- Proven design - implementation of Material Design principles
- Advanced theming system - easy customization of the entire application look
- Excellent documentation - detailed examples and explanations
- Large community - easy to find help and problem solutions
Chakra UI - Simplicity and Accessibility
What is Chakra UI?
Chakra UI is a modern component library that prioritizes simplicity, modularity, and accessibility. It is like building a lightweight, agile space vehicle that is simultaneously safe and easy to operate for every crew member, regardless of their abilities.
Installing Chakra UI
# Installing Chakra UI
npm i @chakra-ui/react @emotion/react @emotion/styled framer-motionConfiguring Chakra UI
// In the main application file
import { ChakraProvider } from '@chakra-ui/react';
function App() {
return (
<ChakraProvider>
{/* Place your components here */}
</ChakraProvider>
);
}Example Usage of Chakra UI
import { Box, Button, Heading, Stack, Text, useColorModeValue } from '@chakra-ui/react';
function SpaceStation() {
// Dynamic colors depending on mode (light/dark)
const bgColor = useColorModeValue('blue.50', 'blue.900');
const textColor = useColorModeValue('gray.800', 'white');
return (
<Box
p={5}
shadow="md"
borderWidth="1px"
borderRadius="md"
bg={bgColor}
color={textColor}
>
<Heading size="md" mb={2}>International Space Station</Heading>
<Text mb={4}>
The orbital home of astronauts and scientists from around the world.
</Text>
<Stack direction="row" spacing={4}>
<Button colorScheme="blue" variant="outline">
Information
</Button>
<Button colorScheme="blue">
Visit
</Button>
</Stack>
</Box>
);
}Styles and Responsiveness in Chakra UI
Chakra UI offers an intuitive way to define responsive styles:
<Stack
direction={["column", "row"]} // column on small screens, row on larger
spacing={[2, 4, 6]} // different spacing for different breakpoints
>
<Box
p={[2, 4, 6]} // padding growing with screen size
width={["100%", "50%", "33%"]} // width depending on screen size
bg="blue.500"
>
Panel 1
</Box>
<Box
p={[2, 4, 6]}
width={["100%", "50%", "33%"]}
bg="green.500"
>
Panel 2
</Box>
<Box
p={[2, 4, 6]}
width={["100%", "50%", "33%"]}
bg="purple.500"
display={["none", "block"]} // hidden on smallest screens
>
Panel 3
</Box>
</Stack>Advantages of Chakra UI
- Ease of use - intuitive API and consistent component structure
- Accessibility - components compliant with WCAG and WAI-ARIA
- Responsiveness - easy definition of styles for different breakpoints
- Dark/light mode - built-in support for theme switching
- Customization - easy adaptation of the design system to project needs
Comparing Frameworks - Which to Choose for Your Cosmic Mission?
shadcn/ui
Ideal for:
- Projects where you want full control over component code
- Developers who use Tailwind CSS
- Applications requiring unique design but needing solid foundations
Potential drawbacks:
- Copying code can lead to a larger codebase
- Smaller component library compared to MUI and Chakra
Material-UI
Ideal for:
- Corporate and enterprise projects
- Applications that should be consistent with Google design
- Situations requiring a rich library of advanced components
Potential drawbacks:
- More complex API in some cases
- Styling requires knowledge of the MUI theming system
- Larger package size
Chakra UI
Ideal for:
- Projects where accessibility is a priority
- Developers who value simplicity and intuitive API
- Applications requiring fast prototyping and easy customization
Potential drawbacks:
- Fewer advanced components than MUI
- Smaller community compared to MUI
Integrating Component Frameworks with Other Technologies
All discussed frameworks can be combined with other technologies:
- Forms - integration with React Hook Form or Formik
- State management - cooperation with Redux, MobX, or React Query
- Routing - compatibility with React Router or Next.js
- Animations - extension with Framer Motion or React Spring
Practical Exercise: Create a Space Mission Dashboard
Choose one of the discussed frameworks (shadcn/ui, Material-UI, or Chakra UI) and create a space mission control dashboard containing:
- Main navigation (e.g., side menu or top bar)
- Ship system status cards
- A fuel consumption chart (you can use a charting library compatible with the chosen framework)
- A mission settings form with different field types
Remember about:
- Responsiveness (the dashboard should work on different devices)
- Accessibility (components should be used according to accessibility guidelines)
- Consistent design (use the theming system of the chosen framework)
This exercise will help you understand how component frameworks can accelerate building complex interfaces and help you decide which one best suits your work style and project needs.
Code for this lesson: App.jsx
import React, { useState } from 'react';
// Inline Styles demonstration in React
function InlineStylesDemo() {
const [isHovered, setIsHovered] = useState(null);
const [theme, setTheme] = useState('dark');
// Styles as JavaScript objects
const themes = {
dark: {
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
text: '#ffffff',
accent: '#00d4ff',
card: 'rgba(255, 255, 255, 0.05)',
},
light: {
background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
text: '#1a1a2e',
accent: '#667eea',
card: 'rgba(0, 0, 0, 0.05)',
},
};
const currentTheme = themes[theme];
// Container styles
const containerStyle = {
minHeight: '100vh',
background: currentTheme.background,
padding: '30px',
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
color: currentTheme.text,
transition: 'all 0.5s ease',
};
const headerStyle = {
textAlign: 'center',
marginBottom: '40px',
};
const titleStyle = {
fontSize: '2.5em',
color: currentTheme.accent,
marginBottom: '10px',
};
// Function generating dynamic styles for the card
const getCardStyle = (index) => ({
background: currentTheme.card,
borderRadius: '15px',
padding: '25px',
marginBottom: '20px',
border: `2px solid ${isHovered === index ? currentTheme.accent : 'transparent'}`,
transform: isHovered === index ? 'translateY(-5px)' : 'translateY(0)',
boxShadow: isHovered === index
? `0 10px 30px ${currentTheme.accent}40`
: 'none',
transition: 'all 0.3s ease',
cursor: 'pointer',
});
const buttonStyle = (isActive) => ({
padding: '12px 24px',
margin: '0 10px',
border: `2px solid ${currentTheme.accent}`,
borderRadius: '8px',
background: isActive ? currentTheme.accent : 'transparent',
color: isActive ? '#000' : currentTheme.accent,
fontWeight: 'bold',
cursor: 'pointer',
transition: 'all 0.3s ease',
});
const features = [
{
title: 'Dynamic values',
description: 'Styles can be computed based on props, state, or other data',
},
{
title: 'No conflicts',
description: 'Inline styles are automatically scoped to the component',
},
{
title: 'Runtime calculations',
description: 'Ability to use JavaScript expressions to generate styles',
},
{
title: 'Easy conditionals',
description: 'Simple way to add conditional styles without extra classes',
},
];
return (
<div style={containerStyle}>
<header style={headerStyle}>
<h1 style={titleStyle}>Inline Styles in React</h1>
<p style={{ color: currentTheme.text, opacity: 0.7 }}>
Dynamic styling with JavaScript objects
</p>
</header>
{/* Theme switcher */}
<div style={{ textAlign: 'center', marginBottom: '40px' }}>
<button
style={buttonStyle(theme === 'dark')}
onClick={() => setTheme('dark')}
>
Dark
</button>
<button
style={buttonStyle(theme === 'light')}
onClick={() => setTheme('light')}
>
Light
</button>
</div>
{/* Cards with dynamic styles */}
<div style={{ maxWidth: '800px', margin: '0 auto' }}>
{features.map((feature, index) => (
<div
key={index}
style={getCardStyle(index)}
onMouseEnter={() => setIsHovered(index)}
onMouseLeave={() => setIsHovered(null)}
>
<h3 style={{
color: currentTheme.accent,
marginBottom: '10px',
fontSize: '1.3em'
}}>
{feature.title}
</h3>
<p style={{
lineHeight: 1.6,
opacity: 0.9
}}>
{feature.description}
</p>
</div>
))}
</div>
{/* Code example */}
<div style={{
maxWidth: '800px',
margin: '40px auto',
background: currentTheme.card,
borderRadius: '15px',
padding: '25px',
border: `1px solid ${currentTheme.accent}30`,
}}>
<h3 style={{ color: currentTheme.accent, marginBottom: '15px' }}>
Syntax example:
</h3>
<pre style={{
background: 'rgba(0,0,0,0.3)',
padding: '15px',
borderRadius: '8px',
overflow: 'auto',
fontSize: '14px',
}}>
{`const style = {
backgroundColor: isActive ? 'blue' : 'gray',
padding: \`\${spacing}px\`,
transform: \`scale(\${scale})\`
};
<div style={style}>...</div>`}
</pre>
</div>
<footer style={{
textAlign: 'center',
marginTop: '40px',
opacity: 0.7
}}>
<p>Inline styles are ideal for dynamic, computed styles</p>
</footer>
</div>
);
}
export default InlineStylesDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the best way to override CSS library styles in React without using !important?
Hands-on tasks in the game
- Vertical ordering
Arrange CSS selectors from lowest to highest specificity: