0

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

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

  • I need to use CSS this way because I need to use media queries with javascript variables on it, and this is the only way to do that, can you show me how to load react in the front-end? – Douara Abderrahman Feb 7 at 23:39
  • You can load react on wordpress like on any other site: reactjs.org/docs/add-react-to-a-website.html But it wouldn't persist between the editor and the frontend. – mtthias Feb 9 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.