Render childrens in React component

How to render childrens in react component


You may not that with in the opening and closing tags of a component there can be other tag like div can contain table, list etc. By default React component hide all the components within.

So how to render the children ?

functional component

In the functional component at the end of the render section add

.....
return (
<div>
{props.children}
</div>

)

Class component

In the class component we have to use the this for accessing the props

.....
return (
<div>
{this.props.children}
</div>

)

Create Mui Dark Mode switch using React Context

How to creaye dark theme switch in using Material UI switch and React Context and State Hooks


Material UI or MUI is one word for all UI needs. It is well documented and easy to use. I really enjoyed it.

In this post I would like to demonstrate how to create dark-mode switcher using the React Context and Material UI switch component.

Context

We already covered the dynamic-Context in detail, please use the posts to learn more about Context and the basic step required.

Our context setup with look like the following

//context/themeContext.js
 import React from 'react';

export const ThemeContext = React.createContext({
    theme: 'dark',
    setTheme: () => { }
  })
  
//app.js or _app.js
 
import React, { useState } from 'react'; 
import { ThemeContext } from '../context/themeContext';


function MyApp({ Component, pageProps }) {
  const [theme, setTheme] = useState("light")
  const value = { theme, setTheme };
 

  return (
  
      <ThemeContext.Provider value={value}   >
        <Component {...pageProps} />
      </ThemeContext.Provider>
    
  );
}

Theme Switcher

A MUI customized switch can be used to create a theme switcher. We also need to access the context using the useContext hook. The code will look like the following.

The complete switch snippet can be obtained from Material UI switch documentation page.

import * as React from 'react';
import clsx from 'clsx';
import { styled } from '@mui/system';
import { useSwitch } from '@mui/core/SwitchUnstyled';
import { Tooltip } from '@mui/material';
import { ThemeContext } from '../context/themeContext';
 ...
function MUISwitch(props) {
  const { theme, setTheme } = React.useContext(ThemeContext)
  const { getInputProps, checked, disabled, focusVisible } = useSwitch(props);
  const stateClasses = {
    checked,
    disabled,
    focusVisible,
  };
  var mode = {

  };

 
  React.useEffect(() => {
    const mode = stateClasses.checked ? 'dark' : 'light'
    setTheme(mode)
  }, [stateClasses])
  return (
    <Tooltip title="Theme switcher">
      <SwitchRoot className={clsx(stateClasses)} >
        <SwitchTrack>
          <SwitchThumb className={clsx(stateClasses)} />
        </SwitchTrack>
        <SwitchInput {...getInputProps()} aria-label="Demo switch" />
      </SwitchRoot>
    </Tooltip>

  );
}

export default function UseSwitchesCustom() {
  return <MUISwitch defaultChecked />;
}

The switcher component can be placed anywhere in component tree and it can change the context value, due to dynamic context.

Tracking changes

In order observe changes in state of the switch component , we can use useEffect and the stateClass. Note that there is no event handler attached to the component.

Implement the Theme

The theme can be implemented as you wish, one of the suggested way is to create a component to implement the theme and wrap other components inside it. Such a component can be .

mport React from 'react'
import { createTheme, ThemeProvider, styled } from '@mui/material/styles';
import { ThemeContext } from '../context/themeContext';

export default function BaseTheme(props) {
    const { theme, setTheme } = React.useContext(ThemeContext)
    const theme1 = createTheme(
        {
            palette:
                { mode: theme }
        }
    );

    console.log('Current Theme - ' + JSON.stringify(theme));
    return (
        <div>
            <ThemeProvider theme={theme1} >
                {props.children}
            </ThemeProvider>
        </div>
    )
}

That’s it.

Leave comment and questions

Stores for React and Nextjs apps

How to implement global Stores in Reactjs apps


State management in bigger application become tedious in Reactjs apps as in other Frameworks. In Vuejs we have a Vuex store which is nice and cool, when come to Nuxtjs, it get simpler.

For react developers there is good library called Redux package, for keeping global state. It is super complicated, I suggest you to use the Redux Toolkit which automate the creation of store

Another way to use super light weight SWR , a cache management solution for your React app.

Here is the official sites

https://swr.vercel.app/

https://swr.vercel.app/

Posts for further reading