Issues receiving parameters in High Order Components in React

37 Views Asked by At

I want to adjust a demo provided by some tutorial about React Design Patterns, subject: Higher Order Component.

In the code the argument '2' for an userId is hardcoded inside of the component and can be found in the last line of the component UserInfoForm.

My question: How can I use a parameter here instead, that I can send to the withEditableUser HOC when calling it like this?

withEditableUser(UserInfoForm, 4);

Any help, tips, additional sources to learn this would be highly appreciated.

Here's the HOC with the hardcoded argument:

import {withEditableUser} from './withEditableUser';

export const UserInfoForm  = withEditableUser(({ user, onChangeUser, onSaveUser, onResetUser }) => {
    const { name, email, username } = user || {};

    console.log(user)

    return user ? (
        <>
        <label>
            Name:
            <input value={name} onChange={e => onChangeUser({ name: e.target.value })} />
        </label>
        <label>
            Email:
            <input value={email} onChange={e => onChangeUser({ email: e.target.value })} />
        </label>
        <label>
            Username:
            <input value={username} onChange={e => onChangeUser({ username: e.target.value })} />
        </label>
        <button onClick={onResetUser}>Reset</button>
        <button onClick={onSaveUser}>Save Changes</button>
        </>
    ) : <p>Loading...</p>;
}
, '2');
1

There are 1 best solutions below

0
Osama Malik On

As you implement a HOC, which will be a shareable component so,

It's better to send that variable as prop to component,

The way how it works is, first of all your props will be received by HOC, than from HOC you have to forward these props to child component If needed in child.

As an example you can have a look at

Passing Props from HOC to child

Passing Props through HOC from route