Hello guys. I am learning React now. I’ve been struggling to understand the logic in the following code I provide below.
import './App.css'
const Button = ({ children, ...rest }) => (
<button onClick={() => console.log("ButtonClick")} {...rest}>
{children}
</button>
);
const withClick = (Component) => {
const handleClick = () => {
console.log("WithClick");
};
return(props) => {
return<Component {...props} onClick={handleClick} />;
};
};
const MyButton = withClick(Button);
export default function App() {
return <MyButton onClick={() => console.log("AppClick")}>Submit</MyButton>;
This is how I understand it so far:
We create a functional component Button that accepts two parameters, in this case children prop and a copy of an array or object from elsewhere as a prop. The component returns a button with onClick event listener logging out “ButtonClick” to the console, as well as …rest array or object copy.
Between the opening and closing tags of the button, we use a children’s prop, which will serve as the text the button will hold.
Next, we declare a higher-order function that takes a Component as argument. Inside in the curly braces, we add a handle click arrow function that returns console.log(“WithClick”) to the console. The higher-order function returns a new component consisting of (…props) and onClick that uses the handleClick arrow function as an event handler.
What I understand so far is that this higher-order function will serve as a factory.
Now the questions: Why do we have props in the return statement as a parameter within withClick? It’s so confusing. Does it have to do anything with Button component props or no? What’s this props purpose?
Since we create a new component here: const MyButton = withClick(Button); props from withClick return statement, make sure that any additional props we add to Button will be inherited. I am so confused here.
Also, it looks like we can mutate onClick functionality for props in this case, but only for those that don’t consist of a copy of an array. If you click the button to run this app, you get “WithClick” as a message in the console. The onClick we later assign to the anonymous arrow function of the MyButton component inside the App component won’t have any effect.
Help appreciated!