简体   繁体   中英

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

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM