Styled components css selector

Styled-Components

First you need to install styled-components. In your terminal, type yarn add styled-components . If you are using CodeSandbox, go to «Add Dependency», find styled-components and it will be installed.

As you can see in the above examples, we’re using styled-components by first importing it. Then, we can use the styled method, followed by the element we want to style, styled.div , and then add backticks to denote our template which we can add regular CSS syntax into. As you can see below, there’s a lot going on in here.

import styled from 'styled-components';
const Block = styled.div`
background-color: white;
color: $( color >) => color || "blue">;
padding: 10px;
border: 1px solid $( color >) => color || "blue">;
display: inline-block;
margin: 5px;
cursor: pointer;
&:hover
background-color: lightblue;
>
`;

Access React props from Styled-components

As you can see in the above example, we created this component called Block which is just a rectangle. In there, we add this line: color: $<(< color >) => color || "blue">; . This can be quite confusing even to those experienced with React. What's going on here is we're actually destructuring off of the React props. This is the same as saying: color: $ props.color || "blue">; Still confused? This still might look weird as we didn't explain what the arrow function actually does. Well, this is just a callback function provided by styled-components. It's actually the same as defining a regular JavaScript function:

color: $function(props)
if(props.color)
return props.color;
>
return "blue";
>>

The one lined statement we defined originally is just the above JavaScript simplified with ES6 shorthand: arrow functions & object destructuring. So anyway, this allows you to dynamically set style attributes of this component: Ex B . This creates a Block with green text.

Styled-components hover selector

You can utilize the CSS hover selector easily within a styled-component.

 
const Block = styled.div`
background-color: white;
&:hover
background-color: lightblue;
>
`;

When hovering on this element, see the background-color change.

Источник

Using css selectors in styled components

A theme can also be passed down to a component using the theme prop.,You can also use useContext to access the current theme outside of styled components when working with React Hooks.,Tagged Template Literals are a new feature in ES6. They let you define custom string interpolation rules, which is how we're able to create styled components.

// Define our button, but with the use of props.theme this timeconst Button = styled.button` font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; /* Color the border and text with theme.main */ color: $ props.theme.main>; border: 2px solid $ props.theme.main>;`; // We are passing a default theme for Buttons that arent wrapped in the ThemeProviderButton.defaultProps = < theme: < main: "palevioletred" >> // Define what props.theme will look likeconst theme = < main: "mediumseagreen">; render( 
>
);

Answer by Levi Roberson

This is my migration so far:,I want to migrate to using styled-components (CSS-in-JS style) in React.,from official styled components documentation

For complex selector patterns, the ampersand (&) can be used to refer back to the main component. Here are some more examples of its potential usage:

const Thing = styled.div.attrs(< tabIndex: 0 >)` color: blue; &:hover < color: red; // when hovered > & ~ & < background: tomato; // as a sibling of , but maybe not directly next to it > & + & < background: lime; // next to > &.something < background: orange; // tagged with an additional CSS class ".something" > .something-else & < border: 1px solid; // inside another element labeled ".something-else" > ` 

Answer by Trace Blair

Here's another way to solve the problem, using CSS variables:,styled-components allows us to “embed” one component in another like this. When the component is rendered, it pops in the appropriate selector, a class that matches the TextLink styled-component.,The top-level styled-component, Wrapper, doesn't set a z-index… Surely, this must be fine??

Answer by Thiago Portillo

If styled components are React components, can we use props? Yes, we can.,Apart from helping you to scope styles, styled components include the following features:,Note: If styled components are React components, and we can pass props, then can we also use states? The library’s GitHub account has an issue addressing this very matter.

import styled from "styled-components"; const StyledButton = styled.button` min-width: 200px; border: none; font-size: 18px; padding: 7px 10px; /* The resulting background color will be based on the bg props. */ background-color: $ props.bg === "black" ? "black" : "blue"; `; function Profile() < return ( 
Button A Button B
) >

Answer by Sawyer Meza

styled can style any component as long as it accepts a className prop.,Similar to styled-components, emotion allows for emotion components to be targeted like regular CSS selectors when using @emotion/babel-plugin.,To use styles from a styled component but change the element that’s rendered, you can use the as prop.

import styled from '@emotion/styled' const Button = styled.button` color: turquoise; ` render()

Answer by Kailey Donovan

In this lesson, we will learn about the css prop we have at our disposal in styled-components to change the style of a component right in the render function.,We will use this prop to override the text color of a button with the one we define in this prop,12Style a component based on complex props with Styled Components 4m 51s

Answer by Eduardo Kline

styled-components supports SCSS-like syntax for defining styles for a styled component. The preprocessor that uses for transforming CSS is stylis.,We can define styled-components outside of the render method with styled-components .,In this article, we’ll look at creating styled-components with pseudo selectors and creating styled wrappers for other components.

For instance, we can define a wrapper component as follows:

import React from "react";import styled from "styled-components";const StyledWrapper = styled.div` font-weight: bold;`;const Wrapper = (< message >) => < return ;>;export default function App() < return ( 
);>

For instance, we can write the following code to define styles with props and stylis code as follows:

import React from "react";import styled from "styled-components";const Thing = styled.div.attrs(() => (< tabIndex: 0 >))` color: blue; &:hover < color: red; >& ~ & < background: tomato; >& + & < background: lime; >&.foo < background: orange; >.foo & < border: 1px solid $(props.primary ? "red" : "green")>; >`;export default function App() < return ( 
foo abc abc bar baz baz
);>

For instance, we can write:

import React from "react";import styled from "styled-components";const Thing = styled.div` && < color: blue; >`;export default function App() < return ( 
foo
);>

We can pass in a callback to the attrs method so that we can choose the props that the base element receives. For instance, if we have an input and we want it to only receive the value attribute and the size prop, we can write:

import React from "react";import styled from "styled-components";const Input = styled.input.attrs((< value, size >) => (< size, value>))` color: palevioletred; font-size: 1em; margin: $ props.size>; padding: $ props.size>;`;export default function App() < return ( 
);>

Answer by Miles Shepard

With CSS-in-JS, you avoid all that as CSS selectors are scoped automatically to their component. Styles are tightly coupled with their components. This makes it much easier to know how to edit a component’s CSS as there’s never any confusion about how and where CSS is being used., Using Styled Components,In this guide, you will learn how to set up a site with the CSS-in-JS library Styled Components.

Источник

Как использовать стилизованные компоненты в React

От автора: это краткое руководство по изучению стилизованных компонентов, методологии CSS на основе компонентов, используемой в React. Если вы хотите применять стилизованные компоненты в своих проектах, это руководство поможет вам начать работу.

Обзор стилизованных компонентов

Styled Components — это библиотека для React и React Native для написания и управления CSS. Это решение «CSS-in-JS», то есть вы пишете CSS в файлах Javascript (в частности, в компонентах, которые являются файлами Javascript). Это чрезвычайно популярное решение для управления CSS в React: около 8 миллионов загрузок с npm в месяц и 30 тысяч звезд на Github.

Прежде чем углубляться в тему стилизованных компонентов, рекомендуется ознакомиться с React и понять его. Несколько преимуществ библиотеки стилизованных компонентов:

Это простой CSS. Да, вы пишете CSS в файле JS, но синтаксис CSS не изменился.

Вендорные префиксы автоматически добавляются при использовании стилизованных компонентов, повышая производительность в браузерах.

Онлайн курс «JavaScript - фреймворк React.js»

Научитесь создавать SPA и RIA приложения с нуля

На курсе вы научитесь Вы научитесь создавать изоморфные приложения на React Redux, типизировать их с помощью Typescript и работать с различными публичными сервисами.

Весь неиспользуемый CSS и стили автоматически удаляются

Вы вообще не пишете никаких имен классов. Имена классов генерируются автоматически, поэтому нет необходимости управлять методологией именования классов CSS, такой как БЭМ. (Это станет понятнее, когда вы прочтете статью)

Установка стилизованных компонентов

Чтобы начать работу со стилизованными компонентами, вам сначала нужно установить их в свой проект:

Источник

Читайте также:  Найти наибольший элемент матрицы python
Оцените статью