block editor - Using styled-components in the save() function on gutenberg

admin2025-01-07  3

I am trying to use styled-components and other react components on the save() function, but it is not working, the styled-component works just fine on the editor ( edit function ), here is my code for the block:

const { __ } = wp.i18n;  
const { registerBlockType } = wp.blocks;

import styled from 'styled-components';


registerBlockType( 'gutenword-blocks/posts', {
    title: 'Styled Div',
    icon: 'admin-page',
    category: 'layout',


    edit: function( props ) {
        const StyledDiv = styled.div`
            height: 300px;
            width: 300px;
            background: red;
        `;
        return <StyledDiv></StyledDiv>;
    },

    save() {
        const StyledDiv = styled.div`
            height: 300px;
            width: 300px;
            background: red;
        `;
        return <StyledDiv></StyledDiv>;

    },
} );

Expected behavior The block when added should show red square on the editor screen and on the front-end

Current behavior The red square is showing only on the editor and nothing is showing on the frontend

I am trying to use styled-components and other react components on the save() function, but it is not working, the styled-component works just fine on the editor ( edit function ), here is my code for the block:

const { __ } = wp.i18n;  
const { registerBlockType } = wp.blocks;

import styled from 'styled-components';


registerBlockType( 'gutenword-blocks/posts', {
    title: 'Styled Div',
    icon: 'admin-page',
    category: 'layout',


    edit: function( props ) {
        const StyledDiv = styled.div`
            height: 300px;
            width: 300px;
            background: red;
        `;
        return <StyledDiv></StyledDiv>;
    },

    save() {
        const StyledDiv = styled.div`
            height: 300px;
            width: 300px;
            background: red;
        `;
        return <StyledDiv></StyledDiv>;

    },
} );

Expected behavior The block when added should show red square on the editor screen and on the front-end

Current behavior The red square is showing only on the editor and nothing is showing on the frontend

Share Improve this question asked Feb 7, 2019 at 17:32 Douara AbderrahmanDouara Abderrahman 411 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

It looks like styled components relies on react to provide the CSS. Since react is not loaded on the Wordpress frontend you are not seeing any styles.

You can define your CSS inline or enqueue a stylesheet with register_block_type. Check out this link for enqueueing: Applying Styles From a Stylesheet

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736254815a235.html

最新回复(0)