📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Setting Styles Dynamically
  • Scoping Styles with CSS Modules
  • Targeting child elements
  • Using pseudo-selectors
  • Using media queries
  1. Javascript
  2. React Complete Guide

Styling React Components

Recall: We know 2 ways to style components and elements so far.

  1. Inline styling using style object passed into component as style={style}

  • Specific to component

  • But can't apply pseudo-selectors like hover or media queries

  1. Stylesheet import using import ./style.css" that gets compiled by Webpack

  • Styles will apply globally

Note: To add media queries and pseudo-selectors to inline styles, install the popular package Radium.

  • For pseudo-selectors, simply wrap your component inside Radium class when you export component.

  • For media queries, simply wrap your App return statement with StyleRoot component.

Setting Styles Dynamically

To set inline styles dynamically, you can just update the style object!

render() {
  const style = {
    color: blue
  };

  if (this.state.isOff) style.color = "gray";

  return <div style={style}>Hi!</div>;
};

To set classes dynamically, just use an array with the join() method.

render() {
  const classes = [];

  if (this.state.persons.length < 3) {
    classes.push("red");
    // classes = ["red"]
  };
  if (this.state.persons.length < 2) {
    classes.push("bold");
    // classes = ["red", "bold"]
  };

  return <div className={classes.join(" ")}>Hi!</div>;
};

Scoping Styles with CSS Modules

CSS modules allow you to scope styles in a *.module.css file to a specific component, even if those styles would override other stylesheets (e.g. using same class name).

As of react-scripts@2.0.0 and higher, CSS modules are supported. To make them work in prior versions, you need to manually configure the Webpack config:

  1. npm run eject to remove react-scripts and give you full access to Webpack config (as opposed to react-scripts managing it for you).

  2. Update webpack.config.dev.js and webpack.config.prod.js files in new config folder to turn on CSS modules.

  • Note: This works because you're telling Webpack how to bundle the CSS

  1. In the Component.js file, import classes from "./Component.css" to get access to a classes object.

  2. Go to the appropriate element in the return statement and add className={classes.className} (where className is found in your Component.css file).

CSS modules scope your CSS because when Webpack bundles your files, it takes your class names and appends component names and unique hashes like [name]__[local]__[hash]. Then it exposes a JS object that maps your class names to their appended versions using key/value pairs of the form className: [name]__[local]__[hash]. You then use this object in your component.

Pro tip: To make a CSS class global, append :global .class { ... }.

Targeting child elements

A component always returns one element with child elements all inside. To target child elements, you can just use this CSS selector syntax: .Parent child. .Parent will be converted into a unique class name, so child will be uniquely targeted!

Note: You can also just give your child elements their own class.

.App { ... }

.App button { /* <-- targets buttons inside .App */
  color: red;
}

Using pseudo-selectors

Simple. Just add the pseudo-selector to selector that includes a class. The class will be converted:

.App button:hover { ... }

Using media queries

Simple again. Just make sure style rules inside your media query make use of classes.

@media (min-width: 480px) {
  .App { ... }
}
PreviousRendering Lists And ConditionalsNextDebugging React Apps

Last updated 3 years ago