Prop Forwarding
In React, prop forwarding refers to the process of passing props from a parent component to a child component, and then further forwarding those props to another child or a DOM element. This is particularly useful when creating higher-order components (HOCs) or wrapper components that need to pass props down to their children without directly using them.
Why Use Prop Forwarding?
Prop forwarding is useful in scenarios where:
- A wrapper component needs to pass props to a child component or DOM element without modifying them.
- You want to create reusable components that can handle props dynamically.
- You need to forward
refobjects to child components or DOM elements (commonly done usingReact.forwardRef).
Example of Prop Forwarding
import React from 'react';
function Button(props) {
return <button style={props.style}>{props.label}</button>;
}
function Wrapper(props) {
// Forwarding props to the Button component
return <Button {...props} />;
}
function App() {
return (
<Wrapper label="Click Me" style={{ backgroundColor:'blue', color:'white' }}/>
);
}
export default App;
In this example:
- The
Wrappercomponent receives props (labelandstyle) and forwards them to theButtoncomponent using the spread operator ({...props}). - The
Buttoncomponent renders the button with the forwarded props.
Forwarding Refs with React.forwardRef
In addition to forwarding props, React provides a special API called React.forwardRef to forward ref objects to child components or DOM elements. This is particularly useful when you need to access a DOM element or a child component’s instance from a parent component.
import React from 'react';
const Input = React.forwardRef((props, ref) => {
return <inputref={ref}{...props}/>;
});
function App() {
const inputRef = React.useRef();
constfocusInput= () => {
inputRef.current.focus();
};
return (
<>
<Input ref={inputRef} placeholder="Type here..."/>
<button onClick={focusInput} >Focus Input</button>
</>
);
}
export default App;
Below is the Screenshot of above exaample:
In this example:
- The
Inputcomponent usesReact.forwardRefto forward therefto the underlying<input>element. - The
Appcomponent creates arefusingReact.useRefand passes it to theInputcomponent. - The
focusInputfunction uses therefto programmatically focus the input field.
