I just recently discovered axe-core
and want to use it for my website, but I'm having trouble with getting it set up how I hoped. It will run when the page loads, as expected, but I was hoping it would also run again whenever my components re-render, but currently I have to refresh the page I want to scan. Not to mention if I want to see anything about modals, I'd have to enable the modal and hardcode any necessary data those modals might need.
I have my axe-core set up like this (very basic) inside my App.js
:
const ReactDOM = require("react-dom");
if (process.env.NODE_ENV !== "production") {
const axe = require("@axe-core/react");
axe(React, ReactDOM, 2000);
}
I saw another post here but there was no solution.
How can I make axe-core scan when my app re-renders due to state changes or changing pages?
P.S. My site runs React v17.0.2 and I'm using axe-core v4.10.2
I quickly found a ReactJS v17 app and tested it after some tewaks, heres is something that might match your need.
https://codesandbox.io/p/devbox/react-17-forked-qf82ng?workspaceId=ws_3crqHhJ5AU8zpns2SioTCx
Based on the official doc
Call the exported function passing in the React and ReactDOM...
I suspected it's only asking us to use that function on the necessary component.
So I created a useAxe()
hook and added it to an individual component. As the affected component rerenders, it will show the new errors based on the code changes and violations.
The code:
hooks.ts
export const useAxe = () => {
useEffect(() => {
axe(React, ReactDOM, 1000);
}, []);
};
Then, in the target component
import { useAxe } from "../hooks";
const IncomeExpenses = () => {
useAxe(); <--
//...
Now, everytime you do a hot reload and has somehow violoated accessibility rules, it will throrw the messages in the console of the developer tool in browser.