Styled components ref typescript

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to correctly define a reference (React.RefObject) for styled-components (for TypeScript)? #2184

How to correctly define a reference (React.RefObject) for styled-components (for TypeScript)? #2184

Comments

How to correctly define a reference for styled-components?

I wrote the following test code:

import React, from 'react'; import styled, from 'styled-components'; type TModalShadowContainer = StyledComponentClass, any>; const ModalShadowContainer: TModalShadowContainer = styled.div` background-color: black; `; export default class Modal extends Component < private readonly modalRef: RefObject; constructor(props: <>) < super(props); this.modalRef = React.createRef(); > public render(): ReactNode < return ( > ); > > 

The error appears on the line:

Type 'RefObject, <>, <>>>' is not assignable to type 'string | ((instance: Component | StatelessComponent | undefined; theme?: <> | undefined; >, any, any> | null) => any) | RefObject, any, any>> | undefined'. Type 'RefObject, <>, <>>>' is not assignable to type 'RefObject  | undefined; >, any, any>>'. Type 'StyledComponentClass, <>, <>>' is not assignable to type 'Component | StatelessComponent | undefined; theme?: <> | undefined; >, any, any>'. Property 'setState' is missing in type 'StyledComponentClass, <>, <>>'. 

How to describe (define) a ref in TypeScript lang?

Читайте также:  Dynamic typing in java

Since everyone is trying to convince me not to do it, I have to refer to the original sources, namely:

The text was updated successfully, but these errors were encountered:

Источник

How to create a ref using Typescript and styled-components

Solution: You can create multiple refs within your constructor if the elements rendered are static and access the elements using Your code with createRef would look like below Working Demo If you are rendering code snippet dynamically by looping over it, you can create ref in the below manner Solution: Looks like you’re trying to give a ref typed for an input element to another React component. If you are trying to forward the ref to an element inside the component, you can use React’s forwardRef function.

How to access more than one element of Dom in react using React.createRef()

You can create multiple refs within your constructor if the elements rendered are static and access the elements using this.myRef.current

Your code with createRef would look like below

import React from "react"; import "./styles.css"; export default class TodoApp extends React.Component < constructor(props) < super(props); this.greenInputRef = React.createRef(); this.redInputRef = React.createRef(); this.state = < fname: "" >; > green = () => < console.log("green ", this.textInput); /* this.textInput.current.style.backgroundColor = "green"; */ this.greenInputRef.current.style.backgroundColor = "green"; >; red = () => < console.log("red ", this.textInput); /* this.textInput.current.style.backgroundColor = "red"; */ this.redInputRef.current.style.backgroundColor = "red"; >; render() < this.setTextInputRef = input; >>>Green 
< this.setTextInputRef = input; >>>Red
*/> > Green
> Red


); > >

If you are rendering code snippet dynamically by looping over it, you can create ref in the below manner

constructor(props) < super(props); props.data.forEach(item =>< this[`dataRef$] = React.createRef(); >) > . render() < return ( 
< data.map(item =>

> ) >

) >

Reactjs — How to correctly define a reference, How to correctly define a reference for styled-components? I wrote the following test code. This is a refined code, unlike the previous one (How to correctly define a reference (React.RefObject) for

How to create a ref using Typescript and styled-components

Looks like you’re trying to give a ref typed for an input element to another React component. If you are trying to forward the ref to an element inside the Header component, you can use React’s forwardRef function.

Reactjs — How to useRef in Hoc for html element using, How to useRef in Hoc for html element using typescript. Ask Question Asked 1 year, 9 months ago. How to create type when using createRef for Animated.View in TypeScript. 0. how can i get child state value to parent using useRef in reactjs + typescript (hooks) 0. Typescript Idle Timer with UseRef.

How to correctly define a reference (React.RefObject<StyledComponentClass>) for styled-components (for TypeScript)?

type MamkinHackerType = T extends StyledComponentClass, infer ElementType>, infer T, infer H> ? ElementType & React.Component, ElementType> & T & H> : never ; private readonly modalRef = React.createRef>(); 

React createref typescript Code Example, input ref in typescript. ref.current is show objct type unknow. typescript htmlinputelement type file ref current. ref type for the component typescript. ref in typescript. typescript add ref to component. ref.current Object is of type ‘unknown’. React.createRef () typescript. forwarding refs typescript.

How to useRef in Hoc for html element using typescript

ref is added to the html props by React.DetailedHTMLProps that is why you are getting an error. Try:

type TElementType = HTMLInputElement | HTMLTextAreaElement; type TElementWithAttributes = React.DetailedHTMLProps, TElementType> 

How does React.createRef() actually work?, createRef () receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . I have some questions on this. First have look at below component.

Источник

Styled Components & TypeScript — 😍

Styled Components happens to be one of my favorite CSS in JS libraries all time and have been part of almost all of my ReactJS projects. As I’m transitioning most of my projects to include TypeScript, there are things I stumbled along, but there are things that feel perfect. Listing down some of them here.

1. Installing the types

Styled Components library does not ship with types. Instead we have to install it from the Definitely Typed repository.

npm i --save-dev @types/styled-components 

2. Custom props

One of the major advantages of using a CSS-in-JS solution is the ability to pass custom props on runtime and adapt CSS accordingly.

const Heading = styled.h1 active: boolean >>` color: $<(props) => props.active ? "red" : "blue">; `; 

Just as in JSX Elements, you can pass the generic type with <> after the component. Now, your styled-component is typed and there would be a static error on the element if you have not passed active prop. To use it for extending a component:

import Title from "./Title"; const Heading = styled(Title) active: boolean >>` color: $<(props) => props.active ? "red" : "blue">; `; 

However, do note that active as a prop is being passed to the Title component even though it is not explicity said so. If someone adds an optional active prop to the component later, this might be problematic. To avoid this, you can refractor to:

const Heading = styled((active, . rest>) => Title  rest> />)>` color: $<(props) => props.active ? "red" : "blue">; `; 

However, this syntax is obviously more convoluted and creates an extra component. Whether it is worth all the mess for uncovering an accidental prop is upto you.

3. Typing the theme

Styled Components has the ability to specify a theme with the help of ThemeProvider . You can later access the theme with $props.theme.main.something> . Even if we avoid everything else, just the autocomplete from the theme object is worth doing this for. From the docs:

// import original module declarations import 'styled-components' // and extend them! declare module 'styled-components'  export interface DefaultTheme  borderRadius: string colors:  main: string secondary: string > > > 

But manually typing the theme like this is pain, mainly because you have to edit two different files everytime you add or remove something from the theme object. Instead you can do:

import <> from "styled-components"; import theme from "../theme"; declare module "styled-components"  type Theme = typeof theme; export interface DefaultTheme extends Theme <> > 

4. Making use of css prop

There are two css functions in the Styled Components documentation for some reason. Here I’m talking about the css attribute that can be used on an element when the Babel plugin is enabled.

div css=`display: flex;`> > . /div> 

But TypeScript is not aware of this css property and produces an error. I don’t know about you, but those red lines do very well bother me 👻. To get around this, you can add the following to the styled.d.ts :

import <> from "styled-components"; import  CSSProp > from "styled-components"; declare module "react"  interface Attributes  css?: CSSProp | CSSObject; > > 

5. Media templates

There is an easy for specifying media queries from the documentation, but while the syntax for it is user friendly, the implementation by itself is hard to reason about for TypeScript (and as it happens, for new users too). Instead I find myself using a much simpler alternative:

const customMediaQuery = (maxWidth: number) => `@media (max-width: $maxWidth>px)`; const media =  custom: customMediaQuery, desktop: customMediaQuery(922), tablet: customMediaQuery(768), phone: customMediaQuery(576) >; const Content = styled.div` height: 3em; width: 3em; background: papayawhip; /* Now we have our methods on media and can use them instead of raw queries */ $media.desktop> $media.tablet> $media.phone>  < background: palevioletred; >`; render(Content />); 

That one pain point I still have is about the ref . Adding a ref to a styled component still gives me an error, the same as it did an year ago. Otherwise, Styled Components 💙 TypeScript.

Источник

Оцените статью