Pages

Tips for using React Redux Hooks to show or hide React components

Hello coders, We have learned how to create a simple app using React and several other things in our previous blogs. Now, it's time to learn something new and very important that we all have to struggle with. Today, we'll look at how to use React redux hooks to show and hide react components with a single click. But before that, let's know a little bit about React components.


What are React components?

React components are small pieces of code that can be put together to make user interfaces that are very complex. They are written in JavaScript and can be used to make components that can be reused and added to the programs. React components can be used to make custom HTML elements, add functionality to existing elements, and make whole user interfaces.


The react library provides a wide variety of methods for displaying and hiding components. But if you are a beginner with react then you might struggle with this. So, we're here to help you understand the fundamentals while also providing tips on how to show or hide React components with a single click using React redux hooks. 


It seems fairly common in React components to have their own in-built logic for showing and hiding. This confuses issues of what to render and how to show or hide a component. To easily toggle the visibility of any React component, we'll be constructing a basic <Toggle> component using Redux hooks.


First of all, let us take an example to understand how the show/hide component works in the redux state. 

Example:

import React from 'react’;

import {connect} from 'react-redux';


const MyComponent = ({show, onClick}) => {

  return show ? (

    <div>

      Do something awesome here

      <button onClick={onClick}>Ok</button>

    </div>

  ) : null

};


const mapStateToProps = (state) => ({

  show: state.showMyCompoent

});


const mapDispatchToProps = (dispatch) => ({

    onClick: () => dispatch({

      type: 'SHOW_MY_COMPONENT', payload: false

    })

  })

;


export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);


//Reducer

const initialState = {

  showMyComponent: false

  showSomeOtherComponent: false

};


export default (state = initialState, action) => {

  switch (action.type) {

    case 'SHOW_MY_COMPONENT':

      return {...state, showMyComponent: action.payload};

    case 'SHOW_SOME_OTHER_COMPONENT':

      return {...state, showSomeOtherComponent: action.payload};

    default:

      return state;

  }

};

//to show the component we would need to dispatch the following:

dispatch({type: 'SHOW_MY_COMPONENT', payload: true});



In the aforementioned example, it is explained how MyComponent is built into this command and the reducer that shows and hides the components. It combines the how and what of rendering with the when of rendering.


From now onwards, we need to repeat all the boilerplate code that is needed for showing and hiding to show and hide a component.


How to build a Building a <Toggle> component?

As of now, we know how to show and hide the component, but we also need to create a toggle button that instantly switches between showing and hiding the component. 


Based on an external condition, the Toggle> component can display or hide its children. This enables us to eliminate repetitive code from our components, resulting in a cleaner component design.


Steps to using React Redux Hooks to show or hide React components 


Step 1: Utilize the useSelector hook to access the state in your React component.



import React from 'react';

import {useSelector} from 'react-redux';



export const Toggle = ({id, children}) => {

  const show = useSelector(state => state.toggles[id]);

  return show ? children : null;

};



This component requires two values: the first one is the main component and the second one is the child component to show or hide.



const show = useSelector(state => state.toggles[id]);



We have also used a Redux hook to check the Redux state by id.


Step 2. Build a reducer

We have to build a reducer to manage the state of our toggles. U can use the below command to build a reducer that will provide information about toggle stage.


const initialState = {

};


export default (state = initialState, action) => {

  switch (action.type) {

    case 'SHOW':

      return {...state, [action.payload]: true};

    case 'HIDE':

      return {...state, [action.payload]: false};

    default:

      return state;

  }

};


As there is no entry for toggled components in the initial state, they are hidden by default. When the reducer receives a 'SHOW' action, the <Toggle> id (the payload) is added with a true value. A <Toggle> can be hidden again by sending a 'HIDE' action with the <Toggle> id.


The state might look something like this:



{

  errorMessageToggle: true,

  loginFormToggle: false,

  registerUserFormToggle: true

}


Step 3: Create an action

In the third step, we have to create actions that will show/hide the toggle.


export const showToggle = id => ({type: 'SHOW', payload: id});

export const hideToggle = id => ({type: 'HIDE', payload: id});


Step 4: Simplify <MyComponent>

After creating the toggle action, we have to simplify the component so that it knows nothing about showing and hiding.


Here is how you can do this:


import React from 'react';


export const MyComponent = ({onClick}) => {

  return (

    <div>

      Do something awesome here

      <button onClick={onClick}>Ok</button>

    </div>

  )

};


Step 5: Use <Toggle> component

In the last step, we will use <Toggle> which will help the app to show/hide <MyComponent>.


import React from 'react';

import {useDispatch} from 'react-redux';

import {Toggle} from './Toggle';

import {MyComponent} from './MyComponent';

import {showToggle, hideToggle} from './actions';


export const SomeOtherComponent = () => {

  const dispatch = useDispatch();

  const toggleId = 'MY_COMPONENT_TOGGLE';

  return (

    <div>

            <span>Say something<span>

            <Toggle id={toggleId}>

              <MyComponent onClick={() => dispatch(hideToggle(toggleId))}/>

            </Toggle>

            <button onClick={() => dispatch(showToggle(toggleId))}>Show my component</button>

    </div>

)};


We extracted the behavior for displaying and hiding, so <MyComponent> no longer cares about the mechanism for displaying and hiding. This behavior has been abstracted so that it can be reused for any component that needs to be shown and hidden. As a result of removing all boilerplate code, the remaining code is significantly cleaner and better separates concerns. During development and debugging, it is now much simpler to observe the toggle state of components.


Final Thoughts

Using React Redux hooks to show or hide components is a great way to keep your application's state organized and easy to access. With hooks, it's easy to control which components are visible and you don't need any extra libraries. With a few simple lines of code, you can create powerful and dynamic components that are easy to maintain and update.


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...