Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The component styled...has been created dynamically. You may see this warning because you've called styled inside another component

In ReactJS while using styled-component, I face the bellow issue when trying to generate styles dynamically.

Below is the error message The component styled.div with the id of "sc-fzqyvX" has been created dynamically. You may see this warning because you've called styled inside another component. To resolve this only create new StyledComponents outside of any render method and function component. io Error spanshot

Below is my code:

  const getColumn = (ratio) => {
    return (styled.div`
        flex: ${ratio}; 
    `)
  } 

const TableHeaderComponent = ({headers, columnRatio}) => {

return ( 
    <TableHeader>
        {
        headers.map((header, index) => {
            const Column = getColumn(columnRatio[index]);
            return(<Column key={index} >{header}</Column>)
        }) }

    </TableHeader>
 );
}

export default TableHeaderComponent;

I understand that I get this warning because I dynamically generate the styled-component through the getColumn method. But how can I get around this?

I can't get the dynamic 'ratio' value from props, because it keeps changing as I iterate.

Thanks in advance! :)

like image 668
Praveen Dass Avatar asked May 18 '20 16:05

Praveen Dass


2 Answers

you can create a Column component as styles component and make use of props to set the specific attributes

const Column = styled.div`
        flex: ${props => props.ratio}; 
    `

const TableHeaderComponent = ({headers, columnRatio}) => {

return ( 
    <TableHeader>
        {
          headers.map((header, index) => {
            return(
               <Column key={index} ratio={columnRatio[index]}>{header}</Column>
            )
          })
        }

    </TableHeader>
 );
}

export default TableHeaderComponent;
like image 119
Shubham Khatri Avatar answered Nov 05 '22 01:11

Shubham Khatri


This warning comes up to guide you improve your app's performance cause, every time that your component rerender all this components will be recreated to avoid this you must create the styled components outside of any React component. Hope this answer help you

like image 44
Potemkin Avatar answered Nov 05 '22 00:11

Potemkin