Anyhelpisappreciated
Anyhelpisappreciated

Reputation: 69

how to create a function which has a function as one of its arguments react

I'm trying to create a function which takes in a function (in this case a react hook useState function) as one of its arguments in order to simplify the below code (I have shown just 2 columns my actual data has about 30 columns hence why I'm trying to simplify)

const [teamName, setTeamName] = useState('')
const [teamLocation, setTeamLocation] = useState('')

    <div classname="editHere">
    <input value={teamName} onChange={(e) => {  setTeamName(e.target.value) }}/>
    </div>

    <div className="editHere">
    <input value={teamLocation} onChange={(e) => {  setTeamLocation(e.target.value) }}/>
    </div>

I'm trying to do this with the following function

function dropDownRow(value, setValue()) {
        return (
            <div className="editHere">
            <input value={value} onChange={(e) => {  setValue(e.target.value) }}/>
            </div>
        )

    }

and then to return what is shown in the first snippet I wanted to type

{dropDownRow(teamName, setTeamName())}
{dropDownRow(teamLocation, setTeamLocation())}

Obviously this does not work so does anyone have any suggestions on how I could do what I'm trying to achieve?

Upvotes: 0

Views: 40

Answers (2)

Jason
Jason

Reputation: 731

Create your function like this ...

function DropDownRow({ value, setValue }) {
  return (
    <div className="editHere">
      <input value={value} onChange={e => setValue(e.target.value)} />
    </div>
  );
}

and your references should like like ...

      <DropDownRow value={teamName} setValue={setTeamName} />
      <DropDownRow value={teamLocation} setValue={setTeamLocation} />

Example Here ...

Upvotes: 1

Not the best answer
Not the best answer

Reputation: 301

Remove parenthesis here :

function dropDownRow(value, setValue) {

And here :

{dropDownRow(teamName, setTeamName)}
{dropDownRow(teamLocation, setTeamLocation)}

or you can also use a cleaner syntax :

const DropDownRow = ({ value, setValue }) => ...

then

<DropDownRow value={teamName} setValue={setTeamName} />
<DropDownRow value={teamLocation} setValue={setTeamLocation} />

Upvotes: 0

Related Questions