Dynamically DOM value and property change in React JS project.

Suppose you are required to set a button named Update or Delete dynamically. Also, change the CSS class name 'success' for Update and 'danger' for the Delete button. You are required to set the Header of div based on Update and Delete mode.

 To dynamically change the properties of HTML elements in React, you can use the state to control those properties and update them accordingly.  

Here is an example below - 

Code Screenshot

Explain code

  • Actually variable currentMode value M is static as an example. But normally it will come from its parent component.
  • Variable editMode is a boolean type. Here changing its state depending on currentMode value. If the current mode is (Delete) then it is false and if M (Modify) then editMode is true.
  • Finally, in h2 and button tag check the editMode (true or false) to change the DOM element's properties.



Code 👇

import React, { useState, useEffect } from 'react';
import '../../styles/AdminUIPage.css';

function EditCategoryPage() {
    const currentMode = 'M';

    const [editMode, setEditMode] = useState(true);

    useEffect(() => {
        setEditMode(currentMode !== 'D'); // Changing the editMode state. Returing 'true' when mode!=='D' otherwise returning 'false'
    }, [currentMode]);

    return (
        // Dynamically set Header and Button name and class
       
        <div>
             <h2 >{editMode ? 'Update Category' : 'Delete Category'}</h2>
            <button  onClick={handleSubmit}
                className={editMode ? 'btn btn-success float-right ml-2' : 'btn btn-danger float-right ml-2'}>{editMode ? 'Update' : 'Delete'}
            </button>
        </div>
    )
}
export default EditCategoryPage

Post a Comment

0 Comments