raju
raju

Reputation: 6946

using styled-component in react.js

I am first time using styled-component with react.js. My code is in Abc.js and in styles.js I have styled-component code.

 export const StyledPopopDiv = styled.div`
  width: 200px;
  height: 100px;
  background: #cecece;
  position: fixed;
  z-index: 200;
  left: ${state => state.pos.x}px;
  top: {state.pos.y}px;
`;
StyledPopopDiv.displayName = 'StyledPopopDiv';

I am trying to pass state.pos.x in styled-component, but this is giving error Cannot read property 'x' of undefined.

I don't know what to do. Please help.

Upvotes: 0

Views: 421

Answers (3)

You should first of all pass the state as a prop to the styled component example :

// Abc.js

<StyledPopopDiv pos={posState} />

So you can use this prop on your styled component definition as below:

//styled.js 

 export const StyledPopopDiv = styled.div`
  width: 200px;
  height: 100px;
  background: #cecece;
  position: fixed;
  z-index: 200;
  left: ${ props => props.pos.x}px;  // outputs '10px' in this example
  top: ${ props => props.pos.y}px;  // outputs '20px' in this example
`;

A better way/tip is to use destruction/spread operator example :

 export const StyledPopopDiv = styled.div`
  width: 200px;
  height: 100px;
  background: #cecece;
  position: fixed;
  z-index: 200;
  left: ${ ({ pos }) => pos.x}px; 
  top: ${ ({ pos }) => pos.y}px;
`;

Upvotes: 1

Vichu
Vichu

Reputation: 1

interface StyledPopupDivProps{
x:string
}

export const StyledPopopDiv =
styled<LinkProps, "div">("div")`
margin: ${props=>props.x}
`;

and pass

<StyledPopupDiv x={intendedValue}/> 

where its being used.

Upvotes: 0

simka
simka

Reputation: 901

it should be props instead of state, assuming you're using StyledPopupDiv in Abc.js render.

Upvotes: 0

Related Questions