React 5 7 Adding Dynamic Styles

Nous attaquons maintenant la construction du composant ChartBar. Dans ChartBar.js, nous importons React puis la feuille ChartBar.css. La fonction reçoit ses props, et nous exportons le composant par défaut. La structure du rendu se compose de trois <div> imbriquées avec les classes chart-bar, chart-bar__inner et chart-bar__fill, plus un quatrième <div> séparé portant la classe chart-bar__label pour l'étiquette. Toutes les classes correspondent exactement aux sélecteurs du CSS.

Calculer la hauteur dynamique de la barre

Pour que la barre se remplisse en fonction de sa valeur, nous déclarons une variable locale let barFillHeight = '0%'. Ensuite, nous vérifions si props.max est supérieur à zéro pour éviter une division par zéro. Si c'est le cas, nous calculons le pourcentage avec Math.round((props.value / props.max) * 100) + '%'. Le résultat est une chaîne de pourcentage prête à être injectée comme style CSS.

Pour appliquer cette hauteur, nous utilisons l'attribut style de React, qui attend un objet JavaScript. Concrètement on écrit style={{ height: barFillHeight }} : les doubles accolades correspondent à JSX (la première paire) puis à l'objet JS (la seconde paire). Cet attribut est défini sur la <div> du chart-bar__fill pour piloter dynamiquement le remplissage visuel.

Enfin, l'étiquette reçue en prop est affichée via {props.label} à l'intérieur du <div> dédié. Le composant ChartBar est désormais terminé : il ne reste plus qu'à utiliser Chart et à lui transmettre les points de données depuis le composant parent.

  • barFillHeight par défaut à '0%' pour la sécurité.
  • Math.round((value / max) * 100) renvoie un pourcentage arrondi.
  • L'attribut style de React prend un objet JavaScript.

Summary

In this lesson, you'll learn how to build a SharkBar component with dynamic styling in React. The component calculates and applies dynamic CSS values to create a progress bar that fills based on the ratio of a value to a maximum value. Using React's style attribute with JavaScript objects, you'll implement dynamic height calculations that update based on component props, demonstrating how to connect data to visual representations through inline styles.

Key points

  • Create a SharkBar component that accepts props for label, value, and max properties to control bar behavior dynamically
  • Use React's style attribute with JavaScript objects (double curly braces: outer for JSX, inner for object literal) to apply dynamic CSS styles to elements
  • Calculate the bar fill percentage dynamically using Math.round((props.value / props.max) * 100) when props.max is greater than 0
  • Structure the component with separate divs for the bar container, inner fill area, and label display, each with appropriate CSS class names
  • Combine CSS class names (like 'short-bar' and 'short-bar__inner') with inline dynamic styles for complete visual control over the progress bar
  • Use conditional checks (if props.max) to ensure dynamic calculations only occur when valid data is available, preventing division by zero errors

FAQ

Why do we use double curly braces in React style attributes?

The outer braces indicate JSX expression syntax, while the inner braces define a JavaScript object literal. React's style prop requires a JavaScript object as its value, hence the nested brace structure.

How does the dynamic bar fill calculation work?

By dividing the current value by the maximum value and multiplying by 100, then rounding to the nearest integer, you get a percentage between 0-100 that represents how full the progress bar should be displayed.

Why check if props.max is greater than 0 before calculating the fill?

This prevents division by zero errors and ensures the component only calculates the fill percentage when valid data is available, making the component more robust and error-free.