Подключить css в реакт

Different Ways to add CSS in React JS

Hi guys!. In this post, we will be looking at the best ways to add CSS code to your React app.
Undoubtedly, CSS plays a crucial role in making your app user-friendly and visually appealing. There are various ways to add CSS to your React app. Let’s discuss some of them.

1 — External Stylesheet

You can create a new CSS file in your project directory and add your CSS inside it. It can then be imported into your React component or class.
The following code is used to import an external CSS stylesheet.

2 — Inline CSS

Inline CSS is perhaps the most common and quick method to add styles in React. However, it has several drawbacks and is generally discouraged, especially for larger applications. To implement inline CSS, you can create an object containing style references, which can be then called using the style<> attribute.
For example:

const styles =  section:  fontSize: "18px", color: "#292b2c", backgroundColor: "#fff", padding: "0 20px" >, wrapper:  textAlign: "center", margin: "0 auto", marginTop: "50px" > > 
section style=styles.section>> div style=styles.wrapper>> /div> /section> 

3 — Styled Components

Probably the most powerful and useful in my opinion is Styled Components. Styled Components lets you write actual CSS in your JavaScript. The main advantage is that you can add conditional code and use variables and functions within the CSS. You can install Styled Components using the following command:
npm install —save styled-components
Next, you need to import it into your component. Then you can create a new variable that will contain the CSS. The same variable name can be used to an HTML element with the previously added styles on it.

import styled from 'styled-components' // Create a button variable and add CSS const Button = styled.button` background: transparent; border-radius: 3px; border: 2px solid red; color:red; ` //display the HTML return ( div> Button>Button/Button> /div> ); 
Other than these, there are 3 more useful ways you can add CSS (credit to lukeshiru):

4 — CSS Modules

You can also add scoped styles quite easily, you just need to create a file with the extension .module.css, like this:

// ComponentName.module.css .Red  color: #f00; > .Blue  color: #00f; > 
import styles from "./ComponentName.module.css"; 
span className=styles.Red>>This text will be red/span> span className=styles.Blue>>This text will be blue/span> 

5 — Atomic CSS

One of the most popular atomic CSS frameworks out there is Tailwind, by just making it part of your project following their instructions you can just use classNames without even touching CSS.

button className="font-bold bg-blue-600 px-6 py-3 text-white rounded-md">Blue button/button> 

6 — Emotion

Styled-components is not the only library that allows you to create components with styles embeded on them, you have great alternatives out there such as Emotion. The best thing about Emotion is that it’s framework agnostic, so you can take your knowledge to other libraries and frameworks besides React, while being pretty similar to styled-components (so you can in several scenarios just change the import). And there you have it. I am sure there are many more out there but I think these options tick most of the boxes needed when adding CSS to your app. Kindly check out my blog too! Thanks!

Источник

10 способов стилизации React-приложений

React — это библиотека для создания пользовательских интерфейсов, она не имеет собственного подхода к стилизации. Это и хорошо, и плохо одновременно. Разработчик может выбрать любой способ, однако сделать этот выбор совсем непросто.

В этой статье мы разберем 10 различных способов добавления стилей в React-приложение:

Инлайн-стили

Инлайн-стили указываются прямо на самом DOM-элементе в атрибуте style. Мы можем передавать их в JSX в виде объекта, что удобнее, чем перечисление в строке через точку с запятой.

import React from "react"; const container = < padding: 12, background: 'red' >const Homepage = () => < return ( 
>

Welcome to React

This is a simple homepage

); >; export default Homepage;

Внешние таблицы стилей

Классический способ использования стилей — подключение их из внешних css-файлов, его вполне можно использовать и в React-приложении. Единственная проблема — сложно изолировать стили отдельных компонентов друг от друга.

Создаем обычную таблицу стилей:

И импортируем ее в компонент:

 import React from "react"; import "homepage.css"; const Homepage = () => < return ( 

Welcome to React

This is a simple homepage

); >; export default Homepage;

Утилита create-react-app также добавляет PostCSS-обработку стилей.

CSS-модули

CSS-модули решают проблему изоляции стилей, создавая уникальное имя для каждого класса.

Create-react-app поддерживает работу с CSS-модулями.

Можно использовать одно и то же имя класса, не заботясь о возможных конфликтах. Например, мы можем использовать класс .container в разных файлах и у каждого компонента будет контейнер с собственным оформлением:

// homepage.module.css .container < padding:12px; background:red; >// contactpage.module.css .container

Импортируем нужный файл в компоненте:

import React from "react"; import styles from "./homepage.module.css"; // Импорт CSS-модуля import "./another-stylesheet.css"; // Импорт обычного файла стилей const Homepage = () => < return ( 
>

Welcome to React

This is a simple homepage

); >; export default Homepage;

CSS-препроцессоры

Мы можем использовать Sass, Scss, Less, Stylus и другие препроцессоры CSS в React-приложениях, используя специальные лоадеры для Webpack. К сожалению, они не поддерживаются в Create-react-app из коробки.

Например, чтобы использовать Scss или Sass нам нужно установить node-sass:

Styled Components

Пакет styled-component позволяет писать стили как обычный CSS-код, пользуясь при этом всеми преимуществами JS.

Перед началом работы нужно установить npm-модуль:

Стили создаются прямо в файле компонента:

 import React from "react"; import styled from "styled-components"; const Container = styled.div` padding: 12px; background: red; `; const Homepage = () => < return ( 

Welcome to React

This is a simple homepage

); >; export default Homepage;

Styled-Components использует синтаксис шаблонных строк, а точнее теговые шаблоны, для создания стилей.

React JSS

JSS позволяет писать CSS прямо в JS декларативно, без конфликтов и с возможностью переиспользования.

Установите react-jss с помощью npm:

Стили создаются с помощью функции createUseStyles :

import React from "react"; import < createUseStyles >from "react-jss"; const useStyles = createUseStyles(< container: < padding: "20px", backgroundColor: "red" >, button: < backgroundColor: "green", color: "white" >>); const Homepage = () => < const classes = useStyles(); return ( 
>

Welcome to React

This is a simple homepage

); >; export default Homepage;

Для применения стилей используйте хук useStyles .

Radium

Radium — это набор инструментов для создания инлайновых стилей с помощью JavaScript. Radium использует tree-shaking для удаления неиспользуемого кода.

JavaScript не дает возможности использовать псевдоселекторы вроде :hover, :focus и т. д. Radium решает эту проблему.

Сначала установите модуль radium:

А затем просто пишите нужные стили:

import React from "react"; import Radium from 'radium'; const Homepage = () => < const style = < padding:"12px", background:'red', ":hover":< background:'blue' >> return ( 
>

Welcome to React

This is a simple homepage

); >; export default Radium(Homepage);

Перед экспортом оберните ваш компонент в декоратор Radium .

React Shadow

React Shadow создает теневой DOM (Shadow DOM), что дает возможность использовать все плюшки инкапсуляции стилей.

Использование в компоненте:

import React from "react"; import root from "react-shadow"; import styles from "homepage.css"; const Homepage = () => < return (  

Welcome to React

This is a simple homepage

); >; export default Homepage;

JSX Style

jsxstyle — это инлайновая система стилей для React и Preact, которая предоставляет максимально удобный для разработчика способ стилизовать компоненты без ущерба для производительности приложения.

import React from "react"; import < Block >from "jsxstyle"; const Homepage = () => < return ( backgroundColor="#f5f5f5" borderRadius=> 

Welcome to React

This is a simple homepage

); >; export default Homepage;

Утилитарные фреймворки

Утилитарные CSS-фреймворки предназначены для того, чтобы писать стили без CSS. Самый известный из них — tailwindcss.

Create-react-app не поддерживает tailwindcss из коробки, поэтому нам нужно использовать расширенные версии этой утилиты, например, CRACO.

Более подробная информация — в официальной документации.

import React from "react"; const Homepage = () => < return ( 

Welcome to React

This is a simple homepage

); >; export default Homepage;

Какой способ стилизации React-приложений используете вы?

Источник

Adding a Stylesheet

This project setup uses webpack for handling all assets. webpack offers a custom way of “extending” the concept of import beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to import the CSS from the JavaScript file:

Button.css ​

Button.js ​

import React,  Component > from 'react'; import './Button.css'; // Tell webpack that Button.js uses these styles  class Button extends Component   render()   // You can use them as regular CSS styles return div className="Button" />; > > 

This is not required for React but many people find this feature convenient. You can read about the benefits of this approach here. However you should be aware that this makes your code less portable to other build tools and environments than webpack.

In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified .css file in the build output.

If you are concerned about using webpack-specific semantics, you can put all your CSS right into src/index.css . It would still be imported from src/index.js , but you could always remove that import if you later migrate to a different build tool.

Источник

Adding a CSS Modules Stylesheet

Note: this feature is available with react-scripts@2.0.0 and higher.

This project supports CSS Modules alongside regular stylesheets using the [name].module.css file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format [filename]\_[classname]\_\_[hash] .

Tip: Should you want to preprocess a stylesheet with Sass then make sure to follow the installation instructions and then change the stylesheet file extension as follows: [name].module.scss or [name].module.sass .

CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules here.

Button.module.css ​

.error   background-color: red; > 

another-stylesheet.css ​

Button.js ​

import React,  Component > from 'react'; import styles from './Button.module.css'; // Import css modules stylesheet as styles import './another-stylesheet.css'; // Import regular stylesheet  class Button extends Component   render()   // reference as a js object return button className=styles.error>>Error Button/button>; > > 

Result​

No clashes from other .error class names

  button class="Button_error_ax7yz">Error Buttonbutton> 

This is an optional feature. Regular stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the .module.css extension.

Источник

Читайте также:  Creating interface objects java
Оцените статью