Need to update state on stateless component using react-redux

Viewed 2649

I have a component that is connected to a store using react-redux (I have shortened my code for simplicity sake):

const Address = (props) => {
    const { userAddresses, removeAddress } = props
    let { showEdit } = props

    return (
        <div>
            {userAddresses.map(address => (
                <div key={address.id}>
                    <p>{address.name}</p>
                    <Button onClick={removeAddress.bind(this, address)}>Delete</Button>
                </div>
            ))}

            <Button
                onClick={() => { showEdit = true }}>
                Add new
            </Button>

            {showEdit ? (
                // show some edit stuff here!!!
            ): null}
        </div>
    )
}

const mapState = state => {
    return {
        userAddresses: state.account.userAddresses,
        showEdit: false
    }
}

const mapDispatch = (dispatch) => {
    return {
        addAddress: address => dispatch(addUserAddress(address)),
        removeAddress: address => dispatch(removeUserAddress(address)),
    }
}

export default connect(mapState, mapDispatch)(Address)

When you click the button (Add new), a form is supposed to popup (marked as show some edit stuff here!!!). I know this can be easily done if Address was a state component. However, I need to use react-redux, and as far as I know, you have to use a stateless component to use react-redux. Can anyone point me in the right direction?

2 Answers

No, you do not "have to use a stateless/function component" to use React-Redux!

connect accepts both class components and function components (and even "special" React components like React.memo()), and it doesn't matter whether they use component state (or hooks) inside or not.

Also, as a side note, you can simplify your code using the "object shorthand" form of mapDispatch:

const mapDispatch = {
    addAddress : addUserAddress,
    removeAddress : removeUserAddress
}

(Note that that could be even shorter if your prop names were named the same as the functions.)

Keeping to strictly use redux, you should have another action to dispatch when the user clicks the button. Then, a reducer will update the value of the showEdit property, which will cause a re-render of your stateless component allowing you to conditionally render the editing form.

But, this is an information (the visibility or not of the editing form) not useful to the rest of your application, so it could be the case to transform your component into a stateful one and track the showEdit property in the local state.

A third option could be the use of useState hook, but it depends on the version of React you have in your project, because they are currently in alpha...

Related