Loading . . .

Introduction to Mastering ReactJS

Getting Started with ReactJS

Understanding Components in ReactJS

Handling Events in ReactJS

Managing State and Props in ReactJS

Component Lifecycle and Hooks in ReactJS

JSX & Conditional Rendering in ReactJS

Styling React Components

Fragments & Lists in ReactJS


Disclaimer: Educational Purposes Only

The content on this website, including videos and code examples, is for educational purposes only. All demonstrations and designs are fictional and created to illustrate coding techniques. Any resemblance to existing websites or brands is purely coincidental.

The creators and administrators of this website do not claim ownership or affiliation with any existing websites or companies. Users are encouraged to use the information responsibly for learning purposes. Liability for any misuse of the content provided is not accepted.

Download Notes

Styling React Components

Key Topics Covered:

1) Inline Styles and Dynamic Styling.

2) Adding CSS Classes to Components.

3) Using Popular CSS-in-JS Libraries like styled-components and Emotion.

4) Handling dynamic content based on component state or props.

Links:

Styling React Components

Updated App.js File:

App.js


import React, { useState } from 'react';
import './App.css';
import StyledComponentExample from './StyledComponentExample';

const InlineStylingComp = () => {
    const [isHighlighted, setIsHighlighted] = useState(false);

    const inlineStyles = {
        color: isHighlighted ? 'blue' : 'red',
        fontSize: '16px'
    }

    return (<div style={inlineStyles}>Inline Style Example</div>);
}

const ClassToggleComp = () => {
    const [isHighlight, setIsHighlight] = useState(false);

    const handleToggleHighlight = () => {
        setIsHighlight(!isHighlight);
    }

    const highlightClass = isHighlight ? 'highlight' : '';

    return (<div className={highlightClass} onClick={handleToggleHighlight}>CSS Class Example</div>)
}

function App() {
    return (<div>
        <InlineStylingComp />
        <ClassToggleComp />
        <StyledComponentExample />
    </div>);
}

export default App;

Final App.css File:

App.css


div.highlight {
    background-color: green;
}

Final StyledComponentExample.js File:

StyledComponentExample.js


import React, { useState } from "react";
import styled from "styled-components";

const StyledComponent = styled.div`
color: ${(props) => (props.isHighlightNeeded ? 'blue' : 'gray')};
`;

const StyledComponentExample = () => {
    const [isHighlightNeeded, setIsHighlightNeeded] = useState(false);

    return (
        <StyledComponent isHighlightNeeded={isHighlightNeeded} onClick={() => setIsHighlightNeeded(!isHighlightNeeded)}>
            Styled Component Example
        </StyledComponent>
    );
};

export default StyledComponentExample;