React
Modes LC offers a React version of every component to provide an idiomatic experience for React users. You can easily toggle between HTML and React examples throughout the documentation.
Installation
To add Modes LC to your React app, install the package from npm by following the instructions on the installation page.
npm install @metsooutotec/modes-lc-components
Now you can start using components!
Usage
Importing components
Every Modes LC component is available to import as a React component. Note that we’re importing the
<MOLcLineChart>
React component instead of the <mo-button>
custom element in the example below.
import MOLcLineChart from '@metsooutotec/modes-lc-components/dist/react/lc-line-chart'; const MyComponent = () => <MOLcLineChart></MOLcLineChart>; export default MyComponent;
You can find a copy + paste import for each component in the “importing” section of its documentation.
It is possible to cherry-pick React components by importing them individually from
@metsooutotec/modes-lc-components/dist/react/lc-line-chart
for example. This method
“cherry-picking” is recommended in order to
minimize the bundle size. Alternatively you can import the React components from the index:
import { MOLcLineChart } from '@metsooutotec/modes-lc-components/dist/react';
, however this
may result in a larger bundle size.
Handling dark mode
In order for Modes LC components to automatically shift to dark mode, it requires the DOM root tag to
contain the class mo-dark-theme
. One example of doing this is using React’s useEffect to update
the DOM as the theme
dependency changes:
useEffect(() => { const mainHtml = document.getElementsByTagName('html')[0] // toggle for theme switching in Modes UI const updateModesTheme = (theme: Themes) => { if (theme !== Themes.DARK) { mainHtml.classList.add('mo-theme-light'); mainHtml.classList.remove('mo-theme-dark'); } else { mainHtml.classList.add('mo-theme-dark'); mainHtml.classList.remove('mo-theme-light'); } }; updateModesTheme(theme); return () => { // 👇️ removing classes from class list // when the component unmounts mainHtml.classList.remove('mo-theme-dark'); mainHtml.classList.remove('mo-theme-light'); }; }, [theme]);
Alternatively adding the class to html can be done e.g., inside the onClick
function of a
button/switch. This is just one example.
The light mode works without the class name, as it is applied to the :root
, but the dark
theme requires the class name to activate.