Thursday, June 27, 2024

React JSX and CSS

React JSX and CSS

You can use CSS with JSX in React applications. There are several ways to apply CSS styles to JSX elements:

1. Inline Styles

You can apply styles directly to JSX elements using the 'style' attribute, which accepts an object with CSS properties and values.

import React from "react";
const MyComponent = () => {
  const textStyle = {
    color: "blue",
    fontSize: "16px",
    fontWeight: "bold",
  };
  return (
    <div>
      <p style={textStyle}>Hello, World!</p>
    </div>
  );
};
export default MyComponent;

2. External Stylesheets

You can import external CSS files into your React components and apply styles using class names.

import React from "react";
import "./styles.css"; // Import external CSS file
const MyComponent = () => {
  return (
    <div>
      <p className="my-text">Hello, World!</p>
    </div>
  );
};
export default MyComponent;

In 'styles.css':


   .my-text {
     color: blue;
     font-size: 16px;
     font-weight: bold;
   }

3. CSS Modules

React supports CSS Modules, which allows you to write modular CSS stylesheets that are scoped to the component they are imported into.


import React from "react";
import styles from "./MyComponent.module.css"; // Import CSS module
const MyComponent = () => {
  return (
    <div>
      <p className={styles.myText}>Hello, World!</p>
    </div>
  );
};
export default MyComponent;

And in 'MyComponent.module.css':


   .myText {
     color: blue;
     font-size: 16px;
     font-weight: bold;
   }

Using CSS with JSX allows you to style your React components in a flexible and modular way, whether it's applying styles inline, using external stylesheets, or utilizing CSS Modules for scoped styling.

Next: React manifest.json

No comments:

Post a Comment

Hot Topics