ReactJS Styling

react

There are several ways to style React components, depending on your needs and preferences. Here are some common approaches:

  • Inline styles: You can use the style prop to specify inline styles for a component. Inline styles are written as a JavaScript object, with the keys being the style properties and the values being the style values.
import React from 'react';

function Button(props) {
    return (
        <button
            style={{
                color: 'white',
                backgroundColor: 'blue',
                fontSize: '16px',
                padding: '8px 16px'
            }}
            onClick={props.onClick}
        >
            {props.children}
        </button>
    );
}

export default Button;

This defines a Button component with inline styles for the color, background color, font size, and padding.

  • CSS classes: You can use the className prop to apply CSS classes to a component. To define the CSS styles for the classes, you can use a stylesheet or include the styles in the head of your HTML document.
import React from 'react';

function Button(props) {
    return (
        <button className="btn" onClick={props.onClick}>
            {props.children}
        </button>
    );
}

export default Button;
.btn {
    color: white;
    background-color: blue;
    font-size: 16px;
    padding: 8px 16px;
}

This defines a Button component that applies the btn class to the button element, and defines the styles for the btn class in a CSS stylesheet.

  • CSS-in-JS libraries: There are several libraries that allow you to write and apply styles to your React components using JavaScript. These libraries provide a convenient way to style your components without the need for separate stylesheets. Some popular CSS-in-JS libraries for React include styled-components, emotion, and JSS.
import React from 'react';
import styled from 'styled-components';

const StyledButton = styled.button`
  color: white;
  background-color: blue;
  font-size: 16px;
  padding: 8px 16px;
`;

function Button(props) {
    return <StyledButton onClick={props.onClick}>{props.children}</StyledButton>;
}

export default Button;

This defines a Button component that uses the styled-components library to create a StyledButton component with the desired styles. The StyledButton component can be used like any other component in your React application.