DEV Community

FORCHA
FORCHA

Posted on

Patterns that indicate DOM dynamic behavior and corresponding React code.

When converting JavaScript code to React code and deciding when to use useState, you need to look for patterns that indicate dynamic behavior. Dynamic behavior in a web application typically involves changes in the DOM based on user interactions or other events. Here are some common changes that suggest the need for state management:

1. Changes in Element Visibility

  • Example: Showing or hiding elements based on user actions.
  • Pattern: Manipulating display style, toggling CSS classes that control visibility (like adding/removing a hidden class).

JavaScript Example

var element = document.getElementById('element');
element.style.display = 'none'; // Hides the element
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [isVisible, setIsVisible] = useState(true);

// Toggling visibility
<div style={{ display: isVisible ? 'block' : 'none' }}>Content</div>
Enter fullscreen mode Exit fullscreen mode

2. Changes in Text Content

  • Example: Updating button text or other text content based on actions.
  • Pattern: Directly setting textContent or innerHTML.

JavaScript Example

button.textContent = 'New Text';
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [buttonText, setButtonText] = useState('Initial Text');

<button onClick={() => setButtonText('New Text')}>{buttonText}</button>
Enter fullscreen mode Exit fullscreen mode

3. Toggling CSS Classes

  • Example: Adding or removing CSS classes based on conditions.
  • Pattern: Using classList.add, classList.remove, or classList.toggle.

JavaScript Example

element.classList.add('active');
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [isActive, setIsActive] = useState(false);

<div className={isActive ? 'active' : ''}>Content</div>
Enter fullscreen mode Exit fullscreen mode

4. Form Input Values

  • Example: Handling input changes.
  • Pattern: Reading or setting value on input elements.

JavaScript Example

input.value = 'new value';
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [inputValue, setInputValue] = useState('');

<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
Enter fullscreen mode Exit fullscreen mode

5. Attributes

  • Example: Modifying attributes like disabled, checked, or src.
  • Pattern: Directly setting attributes on elements.

JavaScript Example

element.disabled = true;
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [isDisabled, setIsDisabled] = useState(false);

<button disabled={isDisabled}>Click me</button>
Enter fullscreen mode Exit fullscreen mode

6. Conditional Rendering

  • Example: Rendering different components or elements based on conditions.
  • Pattern: Using if statements or ternary operators to append/remove elements.

JavaScript Example

if (condition) {
  document.body.appendChild(element);
} else {
  document.body.removeChild(element);
}
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [condition, setCondition] = useState(false);

{condition ? <Component /> : null}
Enter fullscreen mode Exit fullscreen mode

7. Dynamic Styles

  • Example: Changing inline styles dynamically.
  • Pattern: Setting the style attribute with dynamic values.

JavaScript Example

element.style.color = 'red';
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [color, setColor] = useState('black');

<div style={{ color }}>Text</div>
Enter fullscreen mode Exit fullscreen mode

8. Lists and Arrays

  • Example: Rendering lists based on array data.
  • Pattern: Adding/removing items in arrays and updating the DOM accordingly.

JavaScript Example

const items = ['Item 1', 'Item 2'];
const ul = document.createElement('ul');
items.forEach(item => {
  const li = document.createElement('li');
  li.textContent = item;
  ul.appendChild(li);
});
document.body.appendChild(ul);
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [items, setItems] = useState(['Item 1', 'Item 2']);

<ul>
  {items.map((item, index) => (
    <li key={index}>{item}</li>
  ))}
</ul>
Enter fullscreen mode Exit fullscreen mode

9. Dynamic List Manipulation

  • Example: Adding, removing, or updating items in a list based on user actions.
  • Pattern: Manipulating array content and rendering it to the DOM.

JavaScript Example

let list = document.getElementById('list');
let items = ['Item 1', 'Item 2'];
items.forEach(item => {
  let li = document.createElement('li');
  li.textContent = item;
  list.appendChild(li);
});

// Adding an item
let newItem = 'Item 3';
items.push(newItem);
let newLi = document.createElement('li');
newLi.textContent = newItem;
list.appendChild(newLi);
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [items, setItems] = useState(['Item 1', 'Item 2']);

// Adding an item
const addItem = () => {
  setItems([...items, 'Item 3']);
};

return (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);
Enter fullscreen mode Exit fullscreen mode

10. Form Input Handling

  • Example: Handling form input changes and validations.
  • Pattern: Listening for input events and updating values.

JavaScript Example

let input = document.getElementById('input');
input.addEventListener('input', function(event) {
  console.log(event.target.value);
});
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [inputValue, setInputValue] = useState('');

return (
  <input
    value={inputValue}
    onChange={(e) => setInputValue(e.target.value)}
  />
);
Enter fullscreen mode Exit fullscreen mode

11. Animation Triggers

  • Example: Triggering CSS animations based on user interactions.
  • Pattern: Adding/removing CSS classes to start animations.

JavaScript Example

let box = document.getElementById('box');
box.addEventListener('click', function() {
  box.classList.add('animate');
});
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [animate, setAnimate] = useState(false);

return (
  <div
    id="box"
    className={animate ? 'animate' : ''}
    onClick={() => setAnimate(true)}
  />
);
Enter fullscreen mode Exit fullscreen mode

12. Data Fetching

  • Example: Fetching data from an API and updating the DOM.
  • Pattern: Making asynchronous requests and rendering results.

JavaScript Example

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    document.getElementById('data').textContent = JSON.stringify(data);
  });
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [data, setData] = useState(null);

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []);

return <div id="data">{data ? JSON.stringify(data) : 'Loading...'}</div>;
Enter fullscreen mode Exit fullscreen mode

13. Timer or Interval Updates

  • Example: Updating the DOM based on time intervals.
  • Pattern: Using setInterval or setTimeout to trigger updates.

JavaScript Example

let counter = 0;
setInterval(() => {
  document.getElementById('counter').textContent = counter++;
}, 1000);
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [counter, setCounter] = useState(0);

useEffect(() => {
  const interval = setInterval(() => {
    setCounter(prevCounter => prevCounter + 1);
  }, 1000);

  return () => clearInterval(interval);
}, []);

return <div id="counter">{counter}</div>;
Enter fullscreen mode Exit fullscreen mode

14. Conditional Component Rendering

  • Example: Showing different components based on a condition.
  • Pattern: Using if statements or ternary operators to toggle elements.

JavaScript Example

if (isLoggedIn) {
  document.getElementById('welcome').textContent = 'Welcome, User!';
} else {
  document.getElementById('welcome').textContent = 'Please log in.';
}
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [isLoggedIn, setIsLoggedIn] = useState(false);

return (
  <div id="welcome">
    {isLoggedIn ? 'Welcome, User!' : 'Please log in.'}
  </div>
);
Enter fullscreen mode Exit fullscreen mode

15. Modal Windows

  • Example: Displaying a modal window based on user actions.
  • Pattern: Toggling visibility of modal elements.

JavaScript Example

let modal = document.getElementById('modal');
let openButton = document.getElementById('openModal');
let closeButton = document.getElementById('closeModal');

openButton.addEventListener('click', function() {
  modal.style.display = 'block';
});

closeButton.addEventListener('click', function() {
  modal.style.display = 'none';
});
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [isModalOpen, setIsModalOpen] = useState(false);

return (
  <>
    <button id="openModal" onClick={() => setIsModalOpen(true)}>Open Modal</button>
    {isModalOpen && (
      <div id="modal">
        <button id="closeModal" onClick={() => setIsModalOpen(false)}>Close</button>
        <div>Modal Content</div>
      </div>
    )}
  </>
);
Enter fullscreen mode Exit fullscreen mode

16. Accordion Panels

  • Example: Expanding or collapsing accordion panels.
  • Pattern: Toggling classes or styles for panel visibility.

JavaScript Example

let accordion = document.getElementById('accordion');
accordion.addEventListener('click', function() {
  let panel = this.nextElementSibling;
  panel.style.display = panel.style.display === 'block' ? 'none' : 'block';
});
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [isPanelOpen, setIsPanelOpen] = useState(false);

return (
  <div id="accordion" onClick={() => setIsPanelOpen(!isPanelOpen)}>
    Accordion Header
    <div style={{ display: isPanelOpen ? 'block' : 'none' }}>
      Accordion Content
    </div>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

17. Tabs Navigation

  • Example: Switching content based on selected tab.
  • Pattern: Changing the visible content based on active tab index.

JavaScript Example

let tabs = document.querySelectorAll('.tab');
let contents = document.querySelectorAll('.content');

tabs.forEach((tab, index) => {
  tab.addEventListener('click', function() {
    contents.forEach(content => content.style.display = 'none');
    contents[index].style.display = 'block';
  });
});
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [activeTab, setActiveTab] = useState(0);

return (
  <>
    <div className="tabs">
      {['Tab 1', 'Tab 2', 'Tab 3'].map((tab, index) => (
        <button key={index} onClick={() => setActiveTab(index)}>{tab}</button>
      ))}
    </div>
    <div className="contents">
      {activeTab === 0 && <div>Content 1</div>}
      {activeTab === 1 && <div>Content 2</div>}
      {activeTab === 2 && <div>Content 3</div>}
    </div>
  </>
);
Enter fullscreen mode Exit fullscreen mode

18. Dynamic Styling Based on State

  • Example: Changing styles based on state values.
  • Pattern: Directly modifying the style attribute or using class toggles.

JavaScript Example

let box = document.getElementById('box');
box.style.backgroundColor = 'red';
Enter fullscreen mode Exit fullscreen mode

React Conversion

const [color, setColor] = useState('red');

return (
  <div id="box" style={{ backgroundColor: color }}>Box Content</div>
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)