RE04 Exercises
Practical Exercises
- Create a React functional component using the useRef hook to reference a DOM element.
Task:
Create a functional component named TextInputWithFocus that includes an input element. Use the useRef hook to obtain a reference to the input element. Add a button that, when clicked, sets the focus on the input element.
import React, { useRef } from 'react';
const TextInputWithFocus: React.FC = () => {
const inputEl = useRef<HTMLInputElement>(null);
const onButtonClick = () => {
if(inputEl.current) {
inputEl.current.focus();
}
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</div>
);
};
export default TextInputWithFocus;- Write a brief explanation comparing refs and state in React components.
In React, refs and state serve different purposes and behave differently. State is used to store data that, when changed, should re-render the component. It is mutable and changes to the state are asynchronous. Refs, on the other hand, are used to store a reference to a DOM element or an instance of a component. Changes to refs do not trigger re-renders, making them useful for accessing and interacting with DOM elements or keeping track of values across renders without causing additional renders. Refs are more like instance variables in a class component.
- Refs for DOM Manipulation
Objective: Use refs to manipulate the DOM in a functional component.
Task:
Create a functional component with an input field. Use a ref to change the background color of the input field when it is focused.
import * as React from 'react';
const ColorfulInput: React.FC = () => {
const inputRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
const input = inputRef.current;
if(input) {
const handleFocus = () => { input.style.backgroundColor = 'lightblue'; };
const handleBlur = () => { input.style.backgroundColor = 'white'; };
input.addEventListener('focus', handleFocus);
input.addEventListener('blur', handleBlur);
return () => {
input.removeEventListener('focus', handleFocus);
input.removeEventListener('blur', handleBlur);
};
}
}, []);
return <input ref={inputRef} type="text" />;
};
export default ColorfulInput;- Using Forward Ref
Objective: Understand and implement the forwardRef concept in React.
Task:
Create a component FancyButton that forwards its ref to a button element. Use FancyButton in a parent component and log the button's DOM node.
import React, { forwardRef, useRef, useEffect } from 'react';
const FancyButton = forwardRef<HTMLButtonElement, {}>((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
const ParentComponent: React.FC = () => {
const buttonRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
console.log(buttonRef.current); // Logs the DOM node
}, []);
return <FancyButton ref={buttonRef}>Click me!</FancyButton>;
};
export default ParentComponent;