I'm Samuel FajreldinesI am a specialist in the entire JavaScript and TypeScript ecosystem (including Node.js, React, Angular and Vue.js) I am expert in AI and in creating AI integrated solutions I am expert in DevOps and Serverless Architecture (AWS, Google Cloud and Azure) I am expert in PHP and its frameworks (such as Codeigniter and Laravel). |
Samuel FajreldinesI am a specialist in the entire JavaScript and TypeScript ecosystem. I am expert in AI and in creating AI integrated solutions. I am expert in DevOps and Serverless Architecture I am expert in PHP and its frameworks.
|
In the evolving world of front-end development, styling components efficiently and maintainably has become a crucial aspect of building applications. Styled-components is a popular library in the React ecosystem that leverages the power of CSS-in-JS to enhance the styling process. This comprehensive guide will walk you through why styled-components is a game-changer and how to effectively use it in your React projects.
Styled-components allow you to write CSS directly in your JavaScript files, ensuring that styles are scoped to specific components. This eliminates style conflicts and makes your components self-contained.
You can easily create dynamic styles based on props and state. This flexibility enables you to adjust styles in response to user interactions without the need for complex CSS class manipulations.
By co-locating styles with their respective components, your codebase becomes more organized and maintainable. This approach simplifies the debugging process and enhances readability.
Styled-components handle vendor prefixes automatically, ensuring that your styles are compatible across different browsers without extra effort.
To begin using styled-components in your project, install it via npm or yarn:
npm install styled-components
or
yarn add styled-components
Here's how to create a styled button component:
import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background-color: #6200ee;
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: #3700b3;
}
`;
const App = () => (
<Button>Click Me</Button>
);
export default App;
In this example, we imported styled
from styled-components
and used it to create a styled button
element with CSS styles.
Styled-components allow you to pass props to your styled elements to conditionally apply styles.
const Button = styled.button`
background-color: ${props => props.primary ? '#6200ee' : '#white'};
color: ${props => props.primary ? 'white' : '#6200ee'};
padding: 10px 15px;
border: ${props => props.primary ? 'none' : '2px solid #6200ee'};
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: ${props => props.primary ? '#3700b3' : '#f2e7fe'};
}
`;
const App = () => (
<>
<Button primary>Primary Button</Button>
<Button>Secondary Button</Button>
</>
);
export default App;
By passing the primary
prop, we can toggle the button's styles dynamically.
You can create new styled components by extending existing ones:
const OutlineButton = styled(Button)`
background-color: transparent;
color: #6200ee;
border: 2px solid #6200ee;
&:hover {
background-color: #f2e7fe;
}
`;
Now, OutlineButton
has all the styles of Button
with additional overrides.
Styled-components offer a powerful theming solution using the ThemeProvider
.
import { ThemeProvider } from 'styled-components';
const theme = {
primary: '#6200ee',
secondary: '#03dac6',
};
const Button = styled.button`
background-color: ${props => props.theme.primary};
color: white;
padding: 10px 15px;
`;
const App = () => (
<ThemeProvider theme={theme}>
<Button>Themed Button</Button>
</ThemeProvider>
);
This approach centralizes your color schemes and style variables.
Let's build a basic to-do application to see styled-components in action.
First, create a new React application and install styled-components:
npx create-react-app styled-components-todo
cd styled-components-todo
npm install styled-components
We'll create three components:
App
: The main component.TodoList
: Displays the list of to-dos.TodoForm
: A form to add new to-dos.// src/App.js
import React, { useState } from 'react';
import styled from 'styled-components';
import TodoForm from './TodoForm';
import TodoList from './TodoList';
const Container = styled.div`
max-width: 500px;
margin: 50px auto;
padding: 20px;
background-color: #f2e7fe;
border-radius: 10px;
`;
const Title = styled.h1`
text-align: center;
color: #6200ee;
`;
const App = () => {
const [todos, setTodos] = useState([]);
const addTodo = text => {
const newTodos = [...todos, { text }];
setTodos(newTodos);
};
return (
<Container>
<Title>Styled Components To-Do App</Title>
<TodoForm addTodo={addTodo} />
<TodoList todos={todos} />
</Container>
);
};
export default App;
// src/TodoForm.js
import React, { useState } from 'react';
import styled from 'styled-components';
const Form = styled.form`
display: flex;
margin-bottom: 20px;
`;
const Input = styled.input`
flex: 1;
padding: 10px;
border: 2px solid #6200ee;
border-radius: 5px;
margin-right: 10px;
font-size: 16px;
`;
const Button = styled.button`
background-color: #6200ee;
color: white;
padding: 0 20px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
&:hover {
background-color: #3700b3;
}
`;
const TodoForm = ({ addTodo }) => {
const [value, setValue] = useState('');
const handleSubmit = event => {
event.preventDefault();
if (!value) return;
addTodo(value);
setValue('');
};
return (
<Form onSubmit={handleSubmit}>
<Input
type="text"
placeholder="Add a new task"
value={value}
onChange={e => setValue(e.target.value)}
/>
<Button type="submit">Add</Button>
</Form>
);
};
export default TodoForm;
// src/TodoList.js
import React from 'react';
import styled from 'styled-components';
const List = styled.ul`
list-style: none;
padding-left: 0;
`;
const ListItem = styled.li`
background-color: white;
padding: 15px 20px;
border-bottom: 1px solid #ddd;
&:nth-child(even) {
background-color: #fafafa;
}
`;
const TodoList = ({ todos }) => (
<List>
{todos.map((todo, index) => (
<ListItem key={index}>{todo.text}</ListItem>
))}
</List>
);
export default TodoList;
Start the development server:
npm start
Navigate to http://localhost:3000
to interact with your styled to-do app.
Styled-components revolutionize the way we style React applications by combining the power of JavaScript and CSS. They provide:
By integrating styled-components into your workflow, you enhance both the developer and user experience. This guide has provided you with the knowledge and practical examples to start using styled-components confidently.
createGlobalStyle
for styles that should be applied globally.About Me
Since I was a child, I've always wanted to be an inventor. As I grew up, I specialized in information systems, an area which I fell in love with and live around it. I am a full-stack developer and work a lot with devops, i.e., I'm a kind of "jack-of-all-trades" in IT. Wherever there is something cool or new, you'll find me exploring and learning... I am passionate about life, family, and sports. I believe that true happiness can only be achieved by balancing these pillars. I am always looking for new challenges and learning opportunities, and would love to connect with other technology professionals to explore possibilities for collaboration. If you are looking for a dedicated and committed full-stack developer with a passion for excellence, please feel free to contact me. It would be a pleasure to talk with you! |
SecurityScoreCard
Nov. 2023 - Present
New York, United States
Senior Software Engineer
I joined SecurityScorecard, a leading organization with over 400 employees, as a Senior Full Stack Software Engineer. My role spans across developing new systems, maintaining and refactoring legacy solutions, and ensuring they meet the company's high standards of performance, scalability, and reliability.
I work across the entire stack, contributing to both frontend and backend development while also collaborating directly on infrastructure-related tasks, leveraging cloud computing technologies to optimize and scale our systems. This broad scope of responsibilities allows me to ensure seamless integration between user-facing applications and underlying systems architecture.
Additionally, I collaborate closely with diverse teams across the organization, aligning technical implementation with strategic business objectives. Through my work, I aim to deliver innovative and robust solutions that enhance SecurityScorecard's offerings and support its mission to provide world-class cybersecurity insights.
Technologies Used:
Node.js Terraform React Typescript AWS Playwright and Cypress