I try to develop a block WordPress using webpack. In the save.js file, I try to get the with of the user’s screen to choose the content of the return
I used screen.widh or window.innerWidth. Both return a value without any link with the different devices I tried also to use hooks that give the width when resize. They give the same results.
Could you help me ?
I Said what I hâve tried. I don’t understand what happens. I would like have explanations and, if possible, a solution
I've found a French-English translator and would like to clarify my subject. 1 - the results given by screen.width and window.innerwidth are always the same, whatever the device used. 2 - the alert() functions linked to onclick give a correct result. I'll share my code below:
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { useState, useEffect } from "react";
import React from 'react';
import useScreenSize from './useScreenSize';
export default function save(props) {
const blockProps = useBlockProps.save();
const { petitsEcransSeulement, seuilPetitEcran, simuEcran, } = props.attributes;
const screenSize = 1949;
const screenWidth = 1944;
// Déterminer si le texte doit être rétracté en fonction de la largeur de l'écran et de la valeur de petitsEcransSeulement
const retractable = (petitsEcransSeulement && screenWidth < parseInt(seuilPetitEcran)) || !petitsEcransSeulement;
const classExtension = retractable ? 'wp-block-group hide-extension' : 'wp-block-group';
var ts0=screen.width;
var ts1=0;
var tw1=0;
var tw0 = () => {
const lg = window.innerWidth;
return lg;
}
return (
<div {...blockProps}>
<div name="extension" className={classExtension}>
<InnerBlocks.Content />
</div>
{tw1 = window.innerWidth} {ts1 = screen.width}
<div>ts0 : {ts0}<br/>
ts1 : {ts1}<br/>
tw0 : {tw0()}<br/>
tw1 : {tw1}<br/>
</div>
{retractable && (
<button
className="bouton-extension-retraction"
value= "on" //{ etatInitialRetraction }
onClick="jQuery(this.previousElementSibling).toggle(2000); (this.value == 'on') ? (this.firstChild.className = 'fas fa-angle-up', this.value = 'off') : (this.firstChild.className = 'fas fa-angle-down', this.value = 'on');
"
>
<i className="fas fa-angle-down"> </i>
</button>
)}
{(parseInt(window.innerWidth) >= parseInt(600)) ? (
<div>{screenWidth} Grand écran</div>) : (
<div>{window.innerWidth} Petit écran</div>)
}
<button onclick="ts0 = screen.width; alert(window.innerWidth);alert(test.width);alert({retractable})">Largeur écran</button>
</div>
);
}
I spent many hours trying to figure out why my code wasn't working. I tried to get help from chatGPT ;-( I added test variables to check what screen.width and window.innerwidth were telling me. The results are invariable:
ts0 : 2144 / ts1 : 2144 / tw0 : 1489 / tw1 : 1489 / 1944 Grand écran