- Create a new Magento 2 theme by creating a new directory under app/design/frontend/{Vendor}/{theme-name}.
- Create a new package.json file in your theme directory and add the following dependencies:
{
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"@magento/venia-ui": "^2.4.0",
"@magento/peregrine": "^2.4.0",
"@magento/pagebuilder": "^1.1.0"
}
}
- Run
npm install
to install the dependencies. - Create a new JavaScript file in your theme directory and add your React code.
- Import the required components from the
@magento/venia-ui
and@magento/peregrine
packages. - Export your React component as the default export.
- In your Magento 2 theme directory, create a new layout XML file under
app/design/frontend/{Vendor}/{theme-name}/Magento_Theme/layout/default.xml
. - Add the following code to your layout XML file:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<script src="{Vendor}_{theme-name}::js/main.js"/>
</head>
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="react" template="{Vendor}_{theme-name}::react.phtml" />
</referenceContainer>
</body>
</page>
- Create a new template file
app/design/frontend/{Vendor}/{theme-name}/Magento_Theme/templates/react.phtml
and add the following code:
<div id="root"></div>
<script>
require(['{Vendor}_{theme-name}/js/main'], function () {
require(['react', 'react-dom', 'your-react-component'], function (React, ReactDOM, YourReactComponent) {
ReactDOM.render(React.createElement(YourReactComponent), document.getElementById('root'));
});
});
</script>
- Finally, run
php bin/magento setup:static-content:deploy
to deploy the static content and load your new React JS theme.
Note: This is just a basic outline of the steps involved in creating a Magento 2 theme using React JS. You will need to understand Magento 2 and React JS well to successfully complete a custom theme.