Search code examples
javascriptreactjsstyled-components

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! :)


Solution

  • 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;