Remove defaultProps Warning
November 3, 2024 · AI Conversations
in wp block custom blocks
Here's how you can refactor your code to eliminate the warning:
### Before (Using `defaultProps`)
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
);
};
MyComponent.defaultProps = {
title: 'Default Title',
description: 'Default Description',
};
### After (Using Default Parameters)
const MyComponent = ({ title = 'Default Title', description = 'Default Description' }) => {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
};
### Explanation
– In the refactored version, we destructure `title` and `description` directly in the function parameters and provide default values. This approach avoids the need for `defaultProps` and aligns with the latest practices in React.
### Next Steps
– Review your custom blocks to find instances of `defaultProps` and refactor them using default parameters.
– Test your components to ensure that they still work as expected after the change.
This change should resolve the warning and make your code future-proof against upcoming React changes!
Here's how you can set this up:
### 1. Create the Sidebar in `sidebars.js`
In `sidebars.js`, define a function that returns `InspectorControls` with the desired controls for your custom block.
// sidebars.js
import { InspectorControls } from '@wordpress/block-editor';
import { PanelBody, TextControl, ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
const SidebarControls = ({ attributes, setAttributes }) => {
const { title, showTitle } = attributes;
return (
<InspectorControls>
<PanelBody title={__('Settings', 'your-text-domain')} initialOpen={true}>
<TextControl
label={__('Title', 'your-text-domain')}
value={title}
onChange={(value) => setAttributes({ title: value })}
/>
<ToggleControl
label={__('Show Title', 'your-text-domain')}
checked={showTitle}
onChange={(value) => setAttributes({ showTitle: value })}
/>
</PanelBody>
</InspectorControls>
);
};
export default SidebarControls;
In this example, we add a `TextControl` for a title and a `ToggleControl` for a visibility option. Adjust the controls as needed for your block's specific requirements.
### 2. Import and Use `sidebars.js` in Your Block
Now, in your main block file (e.g., `edit.js` or wherever you define your block), import and use the `SidebarControls` component.
// edit.js or index.js
import { useBlockProps } from '@wordpress/block-editor';
import SidebarControls from './sidebars';
const Edit = ({ attributes, setAttributes }) => {
const blockProps = useBlockProps();
return (
<div {...blockProps}>
<SidebarControls attributes={attributes} setAttributes={setAttributes} />
<h2>{attributes.title}</h2>
{attributes.showTitle && <p>This title is visible.</p>}
</div>
);
};
export default Edit;
### 3. Register the Block and Define Attributes
Ensure that your block attributes are registered correctly to store values from the sidebar controls. For example, in your block registration:
// block.js or index.js
import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
registerBlockType('your-namespace/your-block', {
title: 'Your Block',
category: 'common',
attributes: {
title: {
type: 'string',
default: 'Default Title',
},
showTitle: {
type: 'boolean',
default: true,
},
},
edit: Edit,
save: ({ attributes }) => {
return (
<div>
<h2>{attributes.title}</h2>
{attributes.showTitle && <p>This title is visible.</p>}
</div>
);
},
});
### Summary
– **`sidebars.js`** contains the inspector controls with `PanelBody`, `TextControl`, and `ToggleControl`.
– **`edit.js`** uses `SidebarControls` to render the inspector sidebar within the block editor.
– **`block.js`** registers the block and defines the attributes.
This approach keeps your code modular and organized, making it easier to manage complex blocks.
### 1. Create `block.json`
The `block.json` file is where you define the block's metadata, attributes, and settings. Here’s an example based on your requirements:
{
"apiVersion": 2,
"name": "your-namespace/your-block",
"title": "Your Block",
"category": "common",
"icon": "admin-post",
"description": "A custom block with InspectorControls sidebar.",
"supports": {
"html": false
},
"attributes": {
"title": {
"type": "string",
"default": "Default Title"
},
"showTitle": {
"type": "boolean",
"default": true
}
},
"editorScript": "file:./build/edit.js",
"style": "file:./build/style.css"
}
### Explanation of Fields
– **`name`**: The unique block name (namespace/block-name).
– **`attributes`**: Defines the block’s attributes, which will be used by both the editor and the frontend.
– **`editorScript`** and **`style`**: Paths to the JavaScript and CSS files that WordPress will automatically enqueue for this block in the editor and frontend.
> Note: Paths like `"file:./build/edit.js"` are relative to the `block.json` file and will be handled by WordPress during the build process.
### 2. Update `sidebars.js`
Make sure `sidebars.js` still contains the sidebar controls using `InspectorControls`:
// sidebars.js
import { InspectorControls } from '@wordpress/block-editor';
import { PanelBody, TextControl, ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
const SidebarControls = ({ attributes, setAttributes }) => {
const { title, showTitle } = attributes;
return (
<InspectorControls>
<PanelBody title={__('Settings', 'your-text-domain')} initialOpen={true}>
<TextControl
label={__('Title', 'your-text-domain')}
value={title}
onChange={(value) => setAttributes({ title: value })}
/>
<ToggleControl
label={__('Show Title', 'your-text-domain')}
checked={showTitle}
onChange={(value) => setAttributes({ showTitle: value })}
/>
</PanelBody>
</InspectorControls>
);
};
export default SidebarControls;
### 3. Edit the Block Component (`edit.js`)
In `edit.js`, import and use `SidebarControls` and manage the block rendering logic.
// edit.js
import { useBlockProps } from '@wordpress/block-editor';
import SidebarControls from './sidebars';
const Edit = ({ attributes, setAttributes }) => {
const blockProps = useBlockProps();
return (
<div {...blockProps}>
<SidebarControls attributes={attributes} setAttributes={setAttributes} />
<h2>{attributes.title}</h2>
{attributes.showTitle && <p>This title is visible.</p>}
</div>
);
};
export default Edit;
### 4. Register the Block in JavaScript (`index.js`)
Import `block.json` in your `index.js` to register the block with metadata and link it to the `edit` component:
// index.js
import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
import metadata from './block.json';
registerBlockType(metadata, {
edit: Edit,
save: ({ attributes }) => {
return (
<div>
<h2>{attributes.title}</h2>
{attributes.showTitle && <p>This title is visible.</p>}
</div>
);
},
});
### 5. Build Process
Use a build tool like `Webpack` or `@wordpress/scripts` to bundle your JavaScript and CSS files.
Here's an example command to build your JavaScript files:
npx wp-scripts build
This will generate the `build/edit.js` and `build/style.css` files referenced in `block.json`.
### Summary
1. **`block.json`** defines block metadata, attributes, and scripts/styles.
2. **`sidebars.js`** contains `InspectorControls` for the block sidebar.
3. **`edit.js`** defines the block’s edit view and uses `SidebarControls`.
4. **`index.js`** registers the block using `block.json` and specifies the edit and save components.
Using `block.json` for registration keeps everything modular and leverages WordPress’s block API fully, simplifying the block setup and registration.
Here are a few ways to make changes in `render.php` visible immediately:
1. **Clear Cache**: If you have caching enabled, clearing it can force the updates to be visible. Try clearing your browser cache or any caching plugins.
2. **Disable Server-Side Caching**: Some development environments (like Docker or certain hosting setups) cache PHP files. You can disable this in your environment configuration if it’s interfering.
3. **Use Hot Reloading Solutions for PHP**: There are tools like **Laravel Mix** with a WordPress setup, or a simple script to reload PHP changes, though they may require some additional setup.
4. **Restart the Development Server**: As a last resort, restarting `npm run start` will reload the PHP changes.
1. **Check `watch` Mode**:
Ensure that `npm run start` is in a watch mode. With `@wordpress/scripts`, `npm run start` should watch files by default, but in some cases, it might not be active. Verify the configuration in your `package.json` or build tool configuration to ensure that it’s set to watch for changes.
2. **Vite or Webpack Dev Server**:
If you're using a Docker setup, make sure your file-watching capabilities are configured correctly, as Docker can sometimes interfere with real-time file watching. For instance, with Vite or Webpack Dev Server:
– Check if the file paths are mounted correctly in Docker.
– Ensure that the `poll` option is enabled for Webpack, or use Vite's `watch` mode, which allows it to actively look for changes.
3. **Clear Build Cache**:
Sometimes, cached builds interfere. Try clearing any temporary files:
rm -rf node_modules/.cache
4. **Inspect the Console**:
Look for errors or warnings in the terminal where `npm run start` is running. Any file-watching errors or conflicts may show up there.
5. **Check Docker Syncing**:
If you’re using Docker, make sure your `edit.js` file is correctly synced with the container. Sometimes, file sync issues between host and container can prevent changes from being picked up.
6. **Alternative Commands**:
In some cases, `npm run build` may be necessary to fully regenerate changes if `npm run start` isn't working as expected.
If none of these help, restarting `npm run start` may force the changes through. Let me know if this gets things working!
### 1. **Use Polling Mode**
Docker sometimes struggles with native file-watching due to how file systems are mounted. Enabling polling forces the system to actively check for changes, which works better in Docker environments.
For example, if you’re using Webpack or Vite, you can enable polling in your configuration:
**Webpack**:
// webpack.config.js
module.exports = {
// other configurations...
watchOptions: {
poll: 1000, // Check for changes every second
ignored: /node_modules/,
},
};
**Vite**:
// vite.config.js
export default {
server: {
watch: {
usePolling: true,
},
},
};
### 2. **Ensure Volume Mounting is Correct**
Confirm that the `resources/js` folder (or wherever `edit.js` is located) is mounted correctly in your Docker container. Your `docker-compose.yml` should have something like this:
volumes:
- .:/var/www/html # or the appropriate path in your container
This mounts the host file system to the container, allowing changes on the host to reflect in the container.
### 3. **Set Up a Custom `CHOKIDAR_USEPOLLING` Environment Variable**
Some development servers, like `webpack-dev-server` or `@wordpress/scripts`, can use an environment variable to enable polling. Set `CHOKIDAR_USEPOLLING=true` in your Docker environment to ensure it polls for file changes.
**Example in `docker-compose.yml`:**
environment:
- CHOKIDAR_USEPOLLING=true
### 4. **Restart the Development Server**
Sometimes Docker might still not pick up changes due to synchronization issues. If changes are not reflecting, restarting the `npm run start` process in Docker can refresh the connection. Run:
docker-compose exec <service_name> npm run start
### 5. **Watch for Logs and Errors**
Monitor the terminal where `npm run start` is running for any errors or warnings that might indicate a file-watching or permissions issue.
### Summary of Key Steps:
– **Enable polling** in your bundler (Webpack, Vite) with `watchOptions`.
– **Ensure volume mounting** is correct for your Docker configuration.
– **Set `CHOKIDAR_USEPOLLING=true`** if you’re using chokidar for file watching.
– **Restart** the development server if changes aren’t immediately reflected.
Let me know if these solutions resolve the issue!
"name": "nt-block",
"version": "0.1.0",
"description": "Example block scaffolded with Create Block tool.",
"author": "The WordPress Contributors",
"license": "GPL-2.0-or-later",
"main": "build/index.js",
"scripts": {
"build": "wp-scripts build –webpack-copy-php",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start –webpack-copy-php"
},
"devDependencies": {
"@wordpress/scripts": "^30.4.0"
},
"dependencies": {
"@wordpress/block-editor": "^14.6.0",
"@wordpress/blocks": "^14.0.0",
"@wordpress/components": "^28.11.0",
"@wordpress/i18n": "^5.11.0",
"ajv": "^8.17.1"
}
}
Here’s how to address this:
### 1. Enable Polling for File Watching
To ensure Docker correctly picks up file changes, enable polling mode in `@wordpress/scripts` by adding the `CHOKIDAR_USEPOLLING` environment variable.
In your `docker-compose.yml`, set:
environment:
- CHOKIDAR_USEPOLLING=true
This will help `@wordpress/scripts` poll for changes in files, including PHP files, making it more compatible with Docker.
### 2. Ensure Volumes Are Properly Configured
Confirm that your project folder is mounted properly in Docker. This allows real-time file changes to sync with the container. Here’s an example of what the volume setup might look like in `docker-compose.yml`:
services:
your-service-name:
volumes:
- .:/var/www/html # Adjust based on your project’s directory
### 3. Restart `npm run start` in Docker When Changes Aren't Reflected
If the polling or volume settings don't resolve the issue, it might be necessary to restart `npm run start` within the container whenever you make changes to PHP files. Run this command inside your Docker container:
docker-compose exec <service_name> npm run start
### 4. Add a Watcher for PHP Files (Optional)
As a workaround, you could create a custom watcher script that watches for changes in PHP files and triggers a reload. However, this might add some complexity if only needed occasionally.
### Summary
With these steps:
– **Polling** is enabled via `CHOKIDAR_USEPOLLING=true` for better compatibility with Docker.
– **Volume configuration** ensures files are correctly synced between host and container.
– **Restarting `npm run start`** occasionally forces PHP changes to reflect in Docker.
This setup should help your PHP and JavaScript changes to be recognized consistently in Docker.
networks:
wpbedrock:
driver: bridge
services:
# Nginx Service
nginx:
image: nginx:stable-alpine
container_name: ${APP_NAME}_nginx
ports:
– "2500:80"
links:
– php
volumes:
– ./bedrock:/var/www/html
– ./docker/nginx/site.conf:/etc/nginx/conf.d/default.conf:rw
– ./docker/logs/nginx:/var/logs/nginx:rw
depends_on:
– php
– mysql
networks:
– wpbedrock
# PHP Service
php:
build:
context: .
dockerfile: Dockerfile
container_name: ${APP_NAME}_php
volumes:
– ./bedrock:/var/www/html # Fixed typo in path
ports:
– "2501:9000"
networks:
– wpbedrock
# MySQL Service
mysql:
image: mysql:8.0
container_name: ${APP_NAME}_mysql_db
environment:
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASSWORD}
volumes:
– db_data:/var/lib/mysql
ports:
– "2502:3306"
networks:
– wpbedrock
# # Node Service
# node:
# image: node:latest # Use an appropriate Node.js version
# working_dir: /var/www/html
# volumes:
# – ./bedrock:/var/www/html
# networks:
# – wpbedrock
# Adminer Service
adminer:
image: adminer
container_name: ${APP_NAME}_adminer
ports:
– "2530:8080"
restart: always
networks:
– wpbedrock
volumes:
db_data:
### 1. Ensure `CHOKIDAR_USEPOLLING` is Set (for Node in Docker)
Since you commented out the Node service, it won't start with the current configuration. If you want to include it, uncomment the Node service section and set `CHOKIDAR_USEPOLLING` as an environment variable for the Node service to allow `wp-scripts` to pick up file changes in Docker.
Example:
# Node Service
node:
image: node:latest
working_dir: /var/www/html
environment:
- CHOKIDAR_USEPOLLING=true
volumes:
- ./bedrock:/var/www/html
networks:
- wpbedrock
### 2. Add a Command for the Node Service (Optional)
If you are using `wp-scripts` for development (like `npm run start` or `yarn start`), add a command to the Node service to start it automatically.
Example:
command: ["npm", "run", "start"]
This will start the watch mode when the container is started, automatically updating JavaScript and CSS changes.
### 3. Set Up PHP Service to Restart if Needed
If you notice any sync issues with PHP files, setting `restart: always` or `restart: on-failure` on the PHP service can help it restart automatically, catching any new configurations or minor errors.
Example:
php:
build:
context: .
dockerfile: Dockerfile
container_name: ${APP_NAME}_php
volumes:
- ./bedrock:/var/www/html
ports:
- "2501:9000"
restart: always
networks:
- wpbedrock
### 4. Consider `depends_on` for Node Service (Optional)
If your development setup relies on Node, you can add `depends_on` to the Node service to ensure it starts after PHP and Nginx services.
node:
image: node:latest
working_dir: /var/www/html
environment:
- CHOKIDAR_USEPOLLING=true
volumes:
- ./bedrock:/var/www/html
command: ["npm", "run", "start"]
depends_on:
- php
- nginx
networks:
- wpbedrock
### Summary of Updates
1. Add `CHOKIDAR_USEPOLLING=true` to Node's environment for effective file watching.
2. Uncomment and configure the Node service with `command: ["npm", "run", "start"]`.
3. Use `restart: always` on PHP if needed to handle restarts and sync issues.
4. Add `depends_on` in Node to wait for PHP and Nginx services, ensuring all services are ready for development.
These changes should improve file syncing and handling of code changes in Docker for smooth development with WordPress and Bedrock.
# Use PHP 8.3 FPM Alpine image as base
FROM php:8.3-fpm-alpine
# Install necessary packages
RUN apk –no-cache add
libpng
libpng-dev
libjpeg-turbo
libjpeg-turbo-dev
freetype
freetype-dev
zip
git
curl
&& docker-php-ext-configure gd –with-freetype –with-jpeg=/usr/include
&& docker-php-ext-install gd pdo pdo_mysql mysqli
# Install Node.js, npm, and Yarn
RUN apk –no-cache add nodejs npm
&& npm install -g yarn
# Install Composer directly
RUN curl -sS https://getcomposer.org/installer | php — –install-dir=/usr/local/bin –filename=composer
# Set working directory
WORKDIR /var/www/html
# Copy application files
COPY –chown=www-data:www-data bedrock/ /var/www/html
# Expose port 9000 for PHP-FPM
EXPOSE 9000
# Start PHP-FPM
CMD ["php-fpm"]
using in php conainter
### 1. Enable Polling in Development Scripts
Within the PHP container, add the `CHOKIDAR_USEPOLLING` environment variable to enable polling, as Docker might not pick up file changes without it. You can set this variable directly in your Dockerfile or within the `docker-compose.yml` environment section for the PHP service.
For example, if you modify `docker-compose.yml`:
php:
build:
context: .
dockerfile: Dockerfile
environment:
- CHOKIDAR_USEPOLLING=true
volumes:
- ./bedrock:/var/www/html
ports:
- "2501:9000"
networks:
- wpbedrock
### 2. Run Development Scripts Directly Inside the PHP Container
Since Node.js is installed in the PHP container, you can run `npm run start` or `yarn start` inside this container to start your development build:
docker-compose exec php npm run start
This command will keep running, watching files within the PHP container. With `CHOKIDAR_USEPOLLING=true`, the polling should make `npm run start` responsive to changes in JavaScript, CSS, and PHP files.
### 3. Use Dockerfile Multi-Stage Build (Optional for Production)
If this setup is for development, this should work fine. For production, a multi-stage build that removes development dependencies after building assets can optimize image size and runtime performance.
### Summary
– Set `CHOKIDAR_USEPOLLING=true` in the PHP service environment.
– Run `npm run start` within the PHP container directly.
– Consider multi-stage builds if you deploy this to production for optimized images.
This setup should make the PHP container responsive to file changes for your development workflow!