cdmt
cdmt

Reputation: 913

Styled Components get values from string prop

I have a demo here

I'm trying to create a column layout using styled components

I was trying to pass the widths of the columns in the props.

Is it possible to get values from a strig prop passed to the component

So if I pass

<PageLayout twoCol="60,40">

I'd like to get the values something like

flex-basis: ${props.twoCol.split(',')[0]}'%';

I thought it's s string so can I use split to get the separate values in the string.

This doesn't work. is there another way to do this.

Upvotes: 0

Views: 342

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

Sure you can:

const PageLayout = styled.div`
  flex-basis: ${(props) => props.twoCol.split(",")[0]}%;
`;

But a better option might be passing the values instead of manipulating a string:

<PageLayout twoCol={[60,40]}>

const PageLayout = styled.div`
  flex-basis: ${(props) => props.twoCol[0]}%;
`;

The main problem with your snippet is that you need to write a real CSS inside the string literal:

// not '%' like ${(props) => props.someProp}'%'
flex-basis: ${(props) => props.someProp}%;

Upvotes: 1

Related Questions