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 ahidden
class).
JavaScript Example
var element = document.getElementById('element');
element.style.display = 'none'; // Hides the element
React Conversion
const [isVisible, setIsVisible] = useState(true);
// Toggling visibility
<div style={{ display: isVisible ? 'block' : 'none' }}>Content</div>
2. Changes in Text Content
- Example: Updating button text or other text content based on actions.
-
Pattern: Directly setting
textContent
orinnerHTML
.
JavaScript Example
button.textContent = 'New Text';
React Conversion
const [buttonText, setButtonText] = useState('Initial Text');
<button onClick={() => setButtonText('New Text')}>{buttonText}</button>
3. Toggling CSS Classes
- Example: Adding or removing CSS classes based on conditions.
-
Pattern: Using
classList.add
,classList.remove
, orclassList.toggle
.
JavaScript Example
element.classList.add('active');
React Conversion
const [isActive, setIsActive] = useState(false);
<div className={isActive ? 'active' : ''}>Content</div>
4. Form Input Values
- Example: Handling input changes.
-
Pattern: Reading or setting
value
on input elements.
JavaScript Example
input.value = 'new value';
React Conversion
const [inputValue, setInputValue] = useState('');
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
5. Attributes
-
Example: Modifying attributes like
disabled
,checked
, orsrc
. - Pattern: Directly setting attributes on elements.
JavaScript Example
element.disabled = true;
React Conversion
const [isDisabled, setIsDisabled] = useState(false);
<button disabled={isDisabled}>Click me</button>
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);
}
React Conversion
const [condition, setCondition] = useState(false);
{condition ? <Component /> : null}
7. Dynamic Styles
- Example: Changing inline styles dynamically.
-
Pattern: Setting the
style
attribute with dynamic values.
JavaScript Example
element.style.color = 'red';
React Conversion
const [color, setColor] = useState('black');
<div style={{ color }}>Text</div>
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);
React Conversion
const [items, setItems] = useState(['Item 1', 'Item 2']);
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
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);
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>
);
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);
});
React Conversion
const [inputValue, setInputValue] = useState('');
return (
<input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
);
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');
});
React Conversion
const [animate, setAnimate] = useState(false);
return (
<div
id="box"
className={animate ? 'animate' : ''}
onClick={() => setAnimate(true)}
/>
);
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);
});
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>;
13. Timer or Interval Updates
- Example: Updating the DOM based on time intervals.
-
Pattern: Using
setInterval
orsetTimeout
to trigger updates.
JavaScript Example
let counter = 0;
setInterval(() => {
document.getElementById('counter').textContent = counter++;
}, 1000);
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>;
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.';
}
React Conversion
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div id="welcome">
{isLoggedIn ? 'Welcome, User!' : 'Please log in.'}
</div>
);
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';
});
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>
)}
</>
);
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';
});
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>
);
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';
});
});
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>
</>
);
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';
React Conversion
const [color, setColor] = useState('red');
return (
<div id="box" style={{ backgroundColor: color }}>Box Content</div>
);
Top comments (0)