Gutenberg add style attribute using block filter - wordpress

I'm trying to add a style attribute in the block editor to a block's wrapper using a block filter:
const addStyle = createHigherOrderComponent( ( BlockListBlock ) => {
return ( props ) => {
return <BlockListBlock { ...props } className="my-class" style="color: red" />;
};
}, 'addStyle' );
wp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/add-style', addStyle );
Only the my-class class name is added to the class attribute but no style attribute. Is it possible to add a style attribute as well? The documentation states:
It receives the original BlockListBlock component and returns a new
wrapped component.
but does not say you can add only class names.

For the rendering part it's:
wp.hooks.addFilter('blocks.getSaveContent.extraProps','my-plugin/add-style', function(props, name, atts){
return Object.assign(props, { 'style': 'color: red' });
});
Couldn't figure it out for the edit function tho.

Related

How can I avoid inline styles with React?

The code written below works correctly, but I was told to re-do the code in order to avoid inline styles.
export default class ProductDetail extends Component {
makeStyle(name, value) {
return {
backgroundColor: name === 'Color' ? value : "#1D1F22",
}
}
render() {
return (
<div className='sizesWrapper'>
{size.items.map(item => (
<div
key={item.value}
style={this.makeStyle(size.name, item.value)}
className="productSize"
>
{size.name !== 'Color' && item.value}
</div>
))}
</div>
)
}
}
how can I use CSS to change the backgroud-color of each iteration of item in items array instead of using:
style={this.makeStyle(size.name, item.value)}
You can create a CSS file and import it in your JS file. It will apply the CSS to your component

Add value to existing WP Block Editor setting

I would like to add a 33% to the Wordpress Block "Button". So far it has 25%,50%,75% and 100%. Is it possible to insert my new value into the existing width selector?
I'm guessing Block Filters are the way to go.
I think I also found the way to get the settings object which might then help me to find out what I need to overwrite. However simply adding this code to my admin.js does not produce any output. Where would I need to load this?
const filterBlocks = (settings) => {
if (settings.name !== 'core/buttons') {
return settings
}
console.log(settings);
return settings;
}
Quick solution: Add a custom CSS class in the Buttons' block properties under "Advanced > Additional CSS class(es)" then define the custom width in your theme style.css
Detailed solution:
By using wp.hooks.addFilter() you can add a new control to the Button block with as many extra custom width options as you need. The Button blocks preset widths are defined within the function WidthPanel() of the blocks edit.js function:
function WidthPanel( { selectedWidth, setAttributes } ) {
...
return (
...
<ButtonGroup aria-label={ __( 'Button width' ) }>
{ [ 25, 50, 75, 100 ].map( ( widthValue ) => {
...
}
}
To add a new width value of 33% to the block, we need to add our own new button control to the InspectorControls and then use wp.hooks.addFilter() to add this to the existing core Button block, eg:
index.js
import { createHigherOrderComponent } from '#wordpress/compose';
import { Fragment } from '#wordpress/element';
import { InspectorControls } from '#wordpress/block-editor';
import { PanelBody, Button } from '#wordpress/components';
const withInspectorControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const { setAttributes } = props;
let widthValue = 33; // must be a number
return (
<Fragment>
<BlockEdit {...props} />
<InspectorControls>
<PanelBody title="Custom Width">
<Button
key={widthValue}
isSmall
variant={widthValue}
onClick={() => setAttributes({ width: widthValue })}
>
{widthValue}%
</Button>
</PanelBody>
</InspectorControls>
</Fragment>
);
};
}, 'withInspectorControl');
wp.hooks.addFilter(
'editor.BlockEdit',
'core/button',
withInspectorControls
);
Next, a new additional css style needs to be added that (matches the existing width presets structure) for the new custom width, eg:
style.scss
$blocks-block__margin: 0.5em;
&.wp-block-button__width-33 {
width: calc(33.33% - #{ $blocks-block__margin });
}
And there you have it..
The easiest way to put all the code above together/working is to create your own Gutenberg block (and that in itself can be challenging if you aren't familiar with the process or ReactJS). I too have come across similiar challenges with Gutenberg, so I wanted to provide a detailed solution for this kind of issue that works.

Change parent component background on hover in reactJS

I have following React code
Code
What I would like is to when I hover my "E-commerce" picture App component background should change on "E-commerce" picture background.
So respectively and for other pictures.
I will be very grateful if you help me solve this problem.
Context, according to the React docs, should be used only for truly global state like current user or theme. Using context for components makes them less reusable.
updated code
Your component tree is App -> SolutionBox -> SolutionItem.
You want to "react" to an event in SolutionItem in App but there is SolutionBox inbetween them so you have to thread the event thru SolutionBox to App.
Step 1
Add a prop to SolutionItem called on OnHover, this will be a function call back that any parent component can use to react to changes.
function SolutionsSectionBoxItem({ solutionIMG, onHover }) {
let callOnHover = state => {
if (_.isFunction(onHover)) {
onHover(state);
}
};
return (
<div className="solutions-section-item-box">
<img
src={solutionIMG}
alt=""
onMouseEnter={() => {
callOnHover(true);
}}
onMouseLeave={() => {
callOnHover(false);
}}
className="solutions-section-item-img"
/>
</div>
);
}
Step 2
Add a prop to SolutionBoxItem called on BGChanged, this will again be a function call back that will be called when any solutionitem onhover happens. This function will take a menuName string and pass either the current menu name or default.
function SolutionsSectionBox({ onBGChanged }) {
let callBGChanged = menuName => {
if (_.isFunction(onBGChanged)) {
onBGChanged(menuName);
}
};
return (
<div className="solutions-section-box-box">
<SolutionItem
solutionIMG={Ecommerce}
onHover={state => {
callBGChanged(state === true ? "Ecommerce" : "default");
}}
/>
<SolutionItem
solutionIMG={SalesMarketing}
onHover={state => {
callBGChanged(state === true ? "SalesMarketing" : "default");
}}
/>
<SolutionItem
solutionIMG={Analytics}
onHover={state => {
callBGChanged(state === true ? "Analytics" : "default");
}}
/>
<SolutionItem
solutionIMG={Middleware}
onHover={state => {
callBGChanged(state === true ? "Middleware" : "default");
}}
/>
</div>
);
}
Step 3
In the App component listen for the changes. In here we now set state when ever the mouse enters or leaves a solution item. From here you have to change the background, you are using css to control the background url, this will be harder since you now need css class for each background type. You could use the bgImage state value to change the name of the extra css className like 'AppSalesMarketing', 'AppEcommerce', etc.
export default function App() {
const [bgImage, setbgImage] = useState(E);
const onBGChanged = menuName => {
setbgImage(menuName);
};
return (
<div className={`App ${bgImage === "default" ? "" : `App${bgImage}`}`}>
<SolutionBox onBGChanged={onBGChanged} />
</div>
);
}
In CSS
Leave the original App class but based on the bgImage value add an additional one using the name of the bgImage + App like below to cascade down the updated background-image value.
.AppEcommerce {
background-image: url(https://placekitten.com/600/600);
}
.AppSalesMarketing {
background-image: url(https://placekitten.com/500/800);
}
.AppAnalytics {
background-image: url(https://placekitten.com/800/500);
}
.AppMiddleware {
background-image: url(https://placekitten.com/700/700);
}
Extra
I added lodash to test that the incoming props are functions before I call them, it is good to do defensive programming because you never know who may use your component in the future.
let callBGChanged = menuName => {
if (_.isFunction(onBGChanged)) {
onBGChanged(menuName);
}
};
Two ways to solve the problem. One is passing down a function to update state, the other is to useContext. In this case it makes sense to use context because you are passing down a function through multiple components that do not care about the function.
First thing to do is make the background image dynamic in the div's style and use context:
// Put this outside the component
export const BackgroundContext = React.createContext(null);
// -- snip
const [backgroundImage, setBackgroundImage] = useState(Ecommerce);
const updateBackgroundImage = newImage => setBackgroundImage(newImage);
// -- snip
<BackgroundContext.Provider value={updateBackgroundImage}>
<div className="App" style={{ backgroundImage: `url(${backgroundImage})` }}>
{/* -- snip */}
</BackgroundContext.Provider>
Now in your SolutionsSectionBoxItem component you can import the background context:
import BackgroundContext from "../App";
Then using that context and react's mouseover api, update the selected background image:
const setBackgroundImage = useContext(BackgroundContext);
// -- snip
<img onMouseOver={() => setBackgroundImage(solutionIMG)} {/* -- snip -- */} />
You can read more here: https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down

Add CSS for html selector based on React state?

I'd like to set overflow-y: hidden for the html selector (not an element) based on whether a React class component state variable is true. Is that possible?
If you mean you want to apply the overflow-y to the actual HTML tag then putting this code in the render worked for me
...
render() {
let html = document.querySelector('html');
this.state.test === "test" ? html.style.overflowY = "hidden" : html.style.overflowY = "visible";
return (
....
)
};
You can do
function MyComponent() {
// Set your state somehow
const [something, setSomething] = useState(initialState)
// Use it in your className`
return <div className={!!something && 'class-name'} />
}
If you have multiple class names to work with, a popular package is (aptly named) classnames. You might use it like so:
import cx from 'classnames'
function MyComponent() {
const [something, setSomething] = useState(initialState)
return <div className={cx({
'some-class' : something // if this is truthy, 'some-class' gets applie
})} />
}
Yes, It's possible. You can do this.
function App() {
const [visible, setVisible] = useState(false);
useEffect(() => {
const htmlSelector = document.querySelector("html");
htmlSelector.style.overflowY = visible ? "unset" : "hidden";
}, [visible]);
return (
<button onClick={() => setVisible(prevState => !prevState)}>
Toggle overflow
</button>
);
}
See the full example on CodeSandbox
You can use the style property to set inline CSS:
<div style={{ overflowY: hide ? 'hidden' : 'auto' }}>

view does not change background image

I have a template in which I call a function and I have a directive element,
.container-wrapper{"ng-controller" => "MovieRowCtrl"}
%i.fa.fa-info-circle{"ng-click" => "updateSelectedMovie(movie)"}
#big-box-container{"ng-if" => "rowActive"}
%movie-details{:movie => "selectedMovie"}
The function is inside a directive,
app.directive('movieDetails', MovieDetailsDirectiveFn)
.controller('MovieRowCtrl', ['$scope', '$rootScope', MovieRowCtrlFn]);
function MovieDetailsDirectiveFn($animate) {
return {
restrict: 'E',
scope: {
movie: '=',
},
templateUrl: '../assets/angular-app/templates/_movie-info.html'
}
}
function MovieRowCtrlFn($scope, $rootScope) {
$scope.updateSelectedMovie = function updateVisibleMovieIndexFn(movie) {
$scope.selectedMovie = movie;
$rootScope.$broadcast('movieRowActivated', {targetScopeId: $scope.$id});
$scope.rowActive = true;
}
}
As you can see I set my MovieRowCtrl as controller for the .container-wrapper.
So when the updateSelectedMovie(movie) function fires it sets the $scope.rowActive to true (showing the element) and it inject the _movie-info.html template inside the %movie-details element.
This works fine.
In that _movie-info.html template I have this,
.movie-background{"ng-style" => "{'background-image':'url(https://image.tmdb.org/t/p/w1280{{movie.backdrop}})'}"}
Which results in,
<div class="movie-background" ng-style="{'background-image':'url(https://image.tmdb.org/t/p/w1280/lXOqBOcx1t5A3YhJEIfJZOkigwH.jpg)'}"
style="background-image: url("https://image.tmdb.org/t/p/w1280/nbIrDhOtUpdD9HKDBRy02a8VhpV.jpg");">
So it creates a ng-style, and a normale style attribute for the element.
The problem is that when I fire the updateSelectedMovie(movie) the ng-style attribute gets updated with a new url, but the style attribut does not get changed.
<div class="movie-background" ng-style="{'background-image':'url(https://image.tmdb.org/t/p/w1280/15PbZtjRJ4zgQA8XS0otL70piQi.jpg)'}"
style="background-image: url("https://image.tmdb.org/t/p/w1280/nbIrDhOtUpdD9HKDBRy02a8VhpV.jpg");">
Any ideas why the ng-style gets updated, but the other style does not?
There is not need to use {{}} inside ng-style, use + for string concatenation while concatenating scope variable inside ng-style expression.
.movie-background{"ng-style" =>
"{'background-image':'url(https://image.tmdb.org/t/p/w1280' + movie.backdrop +')'}"}

Resources