Search code examples
react-hooksantd

Why React uses antd's < Pagination />; The component onChange property can be directly bound to setCurrent?


First I used React Hooks: useState

const [current, setCurrent] = useState(1)

Then I want to implement a pager effect using the Pagination component from Antd

< Pagination
simple
pageSize={pageSize}
defaultCurrent={current}
total={posts.length}
onChange={setCurrent}
/>

Now my question is why 'onChange ={setChange}' can do the current state update directly?

This is the code I watched a Youtuber write and I tried it myself, wondering why it works


Solution

  • When you use the onChange function of a primitive component, such as the standard input, the event handler is called with the event object, and you need to extract the value using the event object's properties.

    When you create a component that accepts an onChange function you can decide what you wish to call the event handler with.

    For example, AndD Pagination component is a wrapper around the Pagination component of rc-pagination as you can see here. The onChange handler prop of rc-pagination has this signature:

    onChange?: (page: number, pageSize: number) => void;
    

    and it's called by the internal change handler (handleChange) here with the new page, and the page size:

    onChange(newPage, pageSize);
    

    The internal handleChange is usually called by onClick handlers, and passed the new page's number.

    However, since onChange(newPage, pageSize) accepts 2 paramters (page and number of items in page), passing setCurrent directly prevents you from reacting to pageSize changes. If you want pageSize as well, you'll need to updated the state and the handler function, for example:

    const [pagination, setPagination] = useState({ current: 1, pageSize: 10 })
    
    <Pagination
      onChange={(current, pageSize) => setCurrent({ current, pageSize })}