Home > Software engineering >  Passing function and params through react props
Passing function and params through react props

Time:01-18

I have an dropdown menu with buttons for the dropdown elements and pressing them causes an fucntion call. `

        <div className = "dropdown-container">
        <button className = "dropdown-button"> Sort </button>
        <div className = "dropdown-content">
            <button className = "sort-button" onClick={() => changeFilter(['sort=-Covered_distance'])}> Furthest </button>
            <button className = "sort-button" onClick={() => changeFilter(['sort= Covered_distance'])}> Shortest </button>
            <button className = "sort-button" onClick={() => changeFilter(['sort=-Duration'])}> Longest </button>
            <button className = "sort-button" onClick={() => changeFilter(['sort= Duration'])}> Fastest </button>
        </div>
    </div>

Im trying to clean up my code as I have multiple dropdown menus next to each other with the same principle. I thought about making a react component that has the structure of the dropdown menu but as I have an function call in it I need to pass this through also so like.

        <div className = "filters-container">
            <Dropdown changeFilter = { () => changeFilter() }/>
        </div>

Now this works as it calls the function changeFilter(), but none of the params from the other component gets called with the call so it basically calls only changeFilter(), when I press any of the buttons. How can I get the params with the call?

CodePudding user response:

You must pass the argument in the changeFilter prop.

For example:

<div className="filters-container">
   <Dropdown changeFilter={() => changeFilter(['sort=-Covered_distance'])} />
</div>

Here's a working example: https://codesandbox.io/s/falling-currying-kd0oco?file=/src/App.js

The problem here is that when you pass a function as a prop, you can't change their parameters inside the component, the parameter has to be passed from the parent.

CodePudding user response:

Pass the paramter ['sort=-Covered_distance'] in changeFilter function like this:

<div className = "filters-container">
   <Dropdown changeFilter={() => changeFilter(['sort=-Covered_distance'])} />
</div
  • Related