Using styled components with props and typescript
styled-component
import styled from 'styled-components';
interface Props {
height: number;
}
export const Wrapper = styled.div<Props>`
padding: 5%;
height: ${(props) => props.height}%;
`;
index
import React, { FunctionComponent } from 'react';
import { Wrapper } from './Wrapper';
interface Props {
className?: string;
title: string;
height: number;
}
export const MainBoardList: FunctionComponent<Props> = ({ className, title, height }) => (
<Wrapper height={height} className={className}>
{title}
</Wrapper>
);
should work
This answer is outdated, the most current answer is here: https://stackoverflow.com/a/52045733/1053772
As far as I can tell there is no official way (yet?) to do this, but you can solve it with a bit of trickery. First, create a withProps.ts
file with the following content:
import * as React from 'react'
import { ThemedStyledFunction } from 'styled-components'
const withProps = <U>() => <P, T, O>(fn: ThemedStyledFunction<P, T, O>) =>
fn as ThemedStyledFunction<P & U, T, O & U>
export { withProps }
Now, inside your .tsx
files, use it like this:
// ... your other imports
import { withProps } from './withProps'
export interface IconProps {
onPress: any;
src: any;
width: string;
height: string;
}
const Icon = withProps<IconProps>()(styled.Image)`
width: ${(p: IconProps) => p.width};
height: ${(p: IconProps) => p.height};
`;
And you should be good to go. It's definitely not ideal and hopefully there will be a way to provide generics to template literals soon in TS, but I guess that for now this is your best option.
Credit is given where credit is due: I copypasted this from here
The easiest way as styled-components docs said:
import styled from 'styled-components';
import Header from './Header';
const NewHeader = styled(Header)<{ customColor: string }>`
color: ${(props) => props.customColor};
`;
// Header will also receive props.customColor
There have been some recent developments and with a new version of Typescript (eg. 3.0.1) and styled-components (eg. 3.4.5) there's no need for a separate helper. You can specify the interface/type of your props to styled-components directly.
interface Props {
onPress: any;
src: any;
width: string;
height: string;
}
const Icon = styled.Image<Props>`
width: ${p => p.width};
height: ${p => p.height};
`;
and if you want to be more precise and ignore the onPress
const Icon = styled.Image<Pick<Props, 'src' | 'width' | 'height'>>`
width: ${p => p.width};
height: ${p => p.height};
`;