Who loves creating apps.

Tag: scss

Modern Web Development

Quel est le meilleur compliment que vous ayez reçu ?

Styling in React with SCSS

SCSS, or Sassy CSS, offers a more dynamic and powerful approach to styling in conjunction with React, it allows for modular and reusable style sheets that can enhance the visual hierarchy and aesthetics of web applications.

  • Import these styles directly into your React components : Use node-sass or dart-sass in your React project to compile SCSS files into CSS.

Learn More about SCSS

React Router

React Router plays a pivotal role in developing single-page applications () by managing the navigation between different views without refreshing the page.

  • Usage: Define routes using <Route> components within a <Router> to map paths to components.

React Router Documentation

Maintenance and Best Practices

Maintaining a React application involves regular dependency updates, code refactoring for performance optimization, and adherence to best practices such as code splitting and the judicious use of PureComponent keeps your application scalable and maintainable.

Dependencies in React projects are managed through package.json. Keeping these dependencies up to date is crucial for security, performance, and accessing new features.

A simple npm command to update all your project’s dependencies to their latest versions :

npm update

Resource :

Code Refactoring for Performance Optimization

Refactoring your React code can significantly impact performance, especially for large and complex applications. This could involve breaking down large components into smaller, more manageable ones, optimizing re-renders with React.memo or useMemo, and ensuring that components only update when necessary.

const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
});

React.memo is a higher order component that tells React to memoize a component. It only rerenders the component if the props change.

Resource:

Code Splitting

Code splitting is a technique that allows you to split your code into smaller chunks which you then load on demand. React supports code splitting via dynamic import().

Example: Using dynamic import() for Code Splittingimport React, { Suspense, lazy } from 'react'; const OtherComponent = lazy(() => import('./OtherComponent')); function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> </div> ); }

Resource:

Using PureComponent Wisely

PureComponent is useful for optimizing class components that re-render frequently. It implements shouldComponentUpdate with a shallow prop and state comparison. This means the component only updates if there’s a change in props or state, preventing unnecessary updates.

Example: Using PureComponentimport React, { PureComponent } from 'react'; class MyComponent extends PureComponent { render() { return <div>{this.props.myProp}</div>; } }

Resource:

Understanding React through Algorithms

React’s declarative nature contrasts with the imperative approach seen in traditional algorithms. An algorithm in React might involve setting state based on user input or API responses, showcasing React’s reactive paradigm.

Algorithm Example: Dynamic List Rendering in App.js

import React, { useState, useEffect } from ‘react’;

function App() {
const [items, setItems] = useState([]);

useEffect(() => {
// Imagine fetching data from an API here
setItems([{ id: 1, text: ‘Learn React’ }, { id: 2, text: ‘Build Projects’ }]);
}, []);

return (
<div>
{items.map(item => (
<div key={item.id}>{item.text}</div>
))}
</div>
);
}

export default App;

Reflecting on Compliments

Transitioning from the technical to the personal, the finest compliment I’ve ever received was about my ability to simplify complex concepts, making them accessible to others. This feedback, beyond its immediate warmth, underscored the importance of clear communication in education and knowledge sharing. It’s a principle that guides both my teaching and writing, especially in articles like this one.


To illustrate an improved version of a React App.js file for a pizza-related application, let’s craft a functional component that showcases a simple pizza menu. This component will import necessary React features, display a list of pizzas, and include a basic interaction to select a pizza. We’ll also touch on organizing this into a scalable structure by importing a hypothetical PizzaMenu component.

Step 1: Set Up Your Project

Ensure you have a React environment set up. If you’re starting from scratch, the easiest way is to use Create React App:npx create-react-app pizza-app cd pizza-app

Step 2: Install Necessary Packages

While this example may not require additional packages, remember that real-world applications might need libraries such as react-router-dom for routing or sass for SCSS styling.

Step 3: Define the PizzaMenu Component

Before we dive into App.js, let’s assume you have a PizzaMenu component in a separate file (PizzaMenu.js). This component could look something like this:

File: PizzaMenu.js

import React from ‘react’;

const PizzaMenu = ({ pizzas, onSelectPizza }) => (
<div>
<h2>Choose Your Pizza</h2>
<ul>
{pizzas.map(pizza => (
<li key={pizza.id} onClick={() => onSelectPizza(pizza)}>
{pizza.name} – {pizza.ingredients.join(‘, ‘)}
</li>
))}
</ul>
</div>
);

export default PizzaMenu;

Step 4: Implement App.js with PizzaMenu Component

Now, let’s refactor App.js to include the PizzaMenu component, demonstrating a functional component structure with hooks for state management.

File: App.js

import React, { useState } from ‘react’;
import PizzaMenu from ‘./PizzaMenu’; // Import the PizzaMenu component

const initialPizzas = [
{ id: 1, name: ‘Margherita’, ingredients: [‘tomato’, ‘mozzarella’, ‘basil’] },
{ id: 2, name: ‘Pepperoni’, ingredients: [‘tomato’, ‘mozzarella’, ‘pepperoni’] },
{ id: 3, name: ‘Four Seasons’, ingredients: [‘tomato’, ‘mozzarella’, ‘mushrooms’, ‘ham’, ‘artichokes’, ‘olives’, ‘oregano’] },
];

function App() {
const [selectedPizza, setSelectedPizza] = useState(null);

const handleSelectPizza = pizza => {
setSelectedPizza(pizza);
console.log(`Selected Pizza: ${pizza.name}`);
};

return (
<div className=”App”>
<h1>Pizza Selection</h1>
<PizzaMenu pizzas={initialPizzas} onSelectPizza={handleSelectPizza} />
{selectedPizza && (
<div>
<h3>You selected: {selectedPizza.name}</h3>
<p>Ingredients: {selectedPizza.ingredients.join(‘, ‘)}</p>
</div>
)}
</div>
);
}

export default App;

This App.js demonstrates a clean, functional approach to building a React application. It imports a PizzaMenu component, uses hooks for state management, and handles user interactions in a straightforward manner.

Hooks are a feature introduced in React 16.8 that allow you to use state and other React features without writing a class. They enable functional components to have access to stateful logic and lifecycle features that were previously only possible with class components. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.

Commonly Used React Hooks

  • useState: This hook allows you to add React state to functional components. When you call it, you receive a pair: the current state value and a function that lets you update it.

const [count, setCount] = useState(0);

  • useEffect: This hook lets you perform side effects in functional components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, unified into a single API.

useEffect(() => { // Code to run on component mount or update return () => { // Cleanup code, similar to componentWillUnmount }; }, [/* dependencies */]);

  • useContext: This hook allows you to access the value of a React context. It makes it easier to consume the context value in functional components without relying on the Consumer component.

const value = useContext(MyContext);

  • useReducer: An alternative to useState, ideal for managing state logic that involves multiple sub-values or when the next state depends on the previous one. It also makes transitioning to Redux easier if needed.

const [state, dispatch] = useReducer(reducer, initialState);

  • useCallback: Returns a memoized callback function. This is useful for passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);

  • useMemo: Returns a memoized value. It only recalculates the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

  • useRef: Returns a mutable ref object whose .current property is initialized to the passed argument. It can be used to store a mutable value that does not cause re-render when updated.

const myRef = useRef(initialValue);

  • useLayoutEffect: It has the same signature as useEffect, but it fires synchronously after all DOM mutations. Use it to read layout from the DOM and re-render synchronously.

Benefits of Hooks

  • Simplified Code: Hooks allow you to use more of React’s features without classes, which can make your code cleaner and easier to understand.
  • Reusability: Custom hooks can encapsulate stateful logic and be shared across components, promoting code reuse.
  • Composition: Hooks offer a more powerful and flexible way to compose software logic compared to patterns like higher-order components (HOCs) and render props.

By providing a more direct API to React’s features, hooks embrace functional programming principles and significantly simplify component logic, making it more predictable and easier to manage.

The stylistic structure of CSS and SCSS

SCSS: The Heart of Styling

SCSS, or Sassy CSS, offers a more dynamic approach to styling with variables, mixins, and nested rules, making our task app not just functional but visually cohesive and appealing.

// Define Variables for Theme Consistency
$primary-color: #007BFF; // Primary button color
$hover-color: #0056b3;   // Button hover state color
$task-bg-color: #f4f4f4; // Background color for tasks
$font-color: white;      // Color for text in buttons
$input-width: 70%;       // Width of the input field

// Mixin for Hover Effects
@mixin hover-effect($color) {
    &:hover {
        background-color: $color;
    }
}

// Input and Button Styles
.input-button-container {
    input[type="text"] {
        padding: 10px;
        font-size: 16px;
        width: $input-width;
        margin-right: 10px;

        @media (max-width: 600px) {
            width: 100%;
            margin: 10px 0;
        }
    }

    button {
        padding: 10px 20px;
        background-color: $primary-color;
        color: $font-color;
        border: none;
        cursor: pointer;
        font-size: 16px;

        @include hover-effect($hover-color);
    }
}

// Task List Styles
.task-list {
    list-style: none;
    padding: 0;

    .task {
        background-color: $task-bg-color;
        margin-bottom: 10px;
        padding: 20px;
        border-radius: 5px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
}

This snippet introduces responsiveness and interactivity through mixins and media queries.

Pure CSS provides the backbone for our application’s styling.

.task-input {
    padding: 10px;
    font-size: 16px;
    width: 70%;
    margin-right: 10px;
}

.task-button {
    padding: 10px 20px;
    background-color: #007BFF;
    color: white;
    border: none;
    cursor: pointer;
    font-size: 16px;
}

.task-button:hover {
    background-color: #0056b3;
}

.task-list {
    list-style: none;
    padding: 0;
}

.task {
    background-color: #f4f4f4;
    margin-bottom: 10px;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

@media (max-width: 600px) {
    .task-input, .task-button {
        width: 100%;
        margin: 10px 0;
    }
}

Explanation:

  1. Task Input and Button: We’ve increased the padding and font size to enhance user experience, making the elements more clickable and readable. The blue color scheme provides a calming effect and high contrast for readability.

  2. Task List: By decluttering the interface, removing default list styles and padding, we’ve placed the focus squarely on the content. Each task stands out against the app’s background, with visual cues like margins and shadows enhancing the user interface.

  3. Responsive Design: A media query ensures that on smaller screens, inputs and buttons adapt to full width, maintaining usability and accessibility across devices.

Angular and much more

Angular’s evolution has taken the development world by storm, beginning with its significant announcement at the ng-Europe conference back in October 2014. Since then, it has become a cornerstone for developing robust and dynamic web applications. This article guides you through setting up a new Angular project named “Task,” emphasizing the creation of a comprehensive task management application.

The Beginning 🚀

The journey into Angular begins with the Angular CLI, a powerful toolset for initializing, developing, and maintaining Angular applications. To kickstart your project:

  1. Angular CLI Installation:
    • Ensure you have Node.js installed, then proceed with Angular CLI installation using npm:
    • npm install -g @angular/cli
  2. Project Initialization:
    • Create a new Angular project “Task” with routing enabled and SCSS for styles:
    • ng new Task --routing=true --style=scss
  3. Component Generation:
    • Generate essential components for managing tasks:
    • ng generate component Tasks
    • ng generate component TaskDetail
    • ng generate component AddTask
  4. Routing Setup:
    • Configure routing in app-routing.module.ts to navigate between components seamlessly:
    • import { NgModule } from '@angular/core';
    • import { RouterModule, Routes } from '@angular/router';
    • import { TasksComponent } from './tasks/tasks.component';
    • import { TaskDetailComponent } from './task-detail/task-detail.component';
    • import { AddTaskComponent } from './add-task/add-task.component';
    • const routes: Routes = [
    • { path: 'tasks', component: TasksComponent },
    • { path: 'task/:id', component: TaskDetailComponent },
    • { path: 'add-task', component: AddTaskComponent },
    • { path: '', redirectTo: '/tasks', pathMatch: 'full' },
    • ];
    • @NgModule({
    • imports: [RouterModule.forRoot(routes)],
    • exports: [RouterModule]
    • })
    • export class AppRoutingModule { }
  5. Backend Integration:
    • Implement TaskService to perform CRUD operations against a backend API:
    • import { Injectable } from '@angular/core';
    • import { HttpClient } from '@angular/common/http';
    • import { Observable } from 'rxjs';
    • import { Task } from './task';
    • @Injectable({
    • providedIn: 'root'
    • })
    • export class TaskService {
    • private apiUrl = 'http://yourapi/tasks';
    • constructor(private http: HttpClient) { }
    • getTasks(): Observable {
       return this.http.get(this.apiUrl);
      }
      
      getTask(id: number): Observable {
       return this.http.get(${this.apiUrl}/${id});
      }
      
      addTask(task: Task): Observable {
       return this.http.post(this.apiUrl, task);
      }
      
      updateTask(task: Task): Observable {
       return this.http.put(${this.apiUrl}/${task.id}, task);
      }
      
      deleteTask(id: number): Observable {
       return this.http.delete(${this.apiUrl}/${id});
      }
      }
  6. Frontend Interaction:
    • Utilize TaskService in TasksComponent to interact with the backend and display tasks:
    • import { Component, OnInit } from '@angular/core';
    • import { TaskService } from '../task.service';
    • import { Task } from '../task';
    • @Component({
    • selector: 'app-tasks',
    • templateUrl: './tasks.component.html',
    • styleUrls: ['./tasks.component.scss']
    • })
    • export class TasksComponent implements OnInit {
    • tasks: Task[];
    • constructor(private taskService: TaskService) { }
    • ngOnInit() {
    •  this.getTasks();
    • }
    • getTasks(): void {
    •  this.taskService.getTasks()
    •    .subscribe(tasks => this.tasks = tasks);
    • }
    • }
  7. Styling:
    • Define styles for your task components to ensure a user-friendly interface:
    • .task-container {
    • margin: auto;
    • width: 50%;
    • padding: 20px;
    • box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    • }
    • .task-item {
    • display: flex;
    • justify-content: space-between;
    • padding: 10px;
    • margin-top: 10px;
    • border: 1px solid #ccc;
    • border-radius: 5px;
    • }
    • .task-title {
    • font-size: 18px;
    • }
    • .delete-button {
    • cursor: pointer;
    • color: red;
    • }

Setting Up Protection 🛡️

Securing your application is paramount, and Angular aids this with built-in CSRF protection. For back-end CSRF protection, use Node.js/Express with csurf and cookie-parser. Ensure Angular’s HttpClientModule is imported in your app.module.ts for front-end CSRF protection.

Building the Task Application’s UI 🎨

The UI of your task application is the face of your project. Angular provides directives like ngFor for listing tasks and ngModel for two-way data binding, significantly easing the development process.

Leveraging Angular Libraries and Frameworks 📚

To further enhance your application, Angular offers integration with various libraries and frameworks like Angular Material for UI components, NGRX for state management, and RxJS for handling asynchronous operations.

Conclusion

The journey through Angular development is filled with vast possibilities. Utilizing Angular CLI, incorporating essential components, and leveraging external libraries can significantly enrich your application, making “Task” a robust, dynamic, and user-friendly task management tool.

© 2024 Kvnbbg.fr

Theme by Anders NorénUp ↑

Verified by MonsterInsights