jeudi 9 mars 2017

Expand/Collapse sidebar with Redux

I am new into Redux and I would like to know if this is the right approach how to implement Expand/Collapse sidebar with same button.

I have React component Sidebar with bool variable "isCollapsed" which initial state is "false" which means sidebar is expanded.

constructor(props){
    super(props)

    this.state = {
        sidebar: { isCollapsed: false }
    }

    this.onClickCollapseSidebar = this.onClickCollapseSidebar.bind(this)
}

And in "onClick" I am calling selfdefined method onClickCollapseSidebar

<a onClick={this.onClickCollapseSidebar}  className="sidebar-control"></a>

And inside "onClickCollapseSidebar" I am dispatching actions for collpase and expand.

onClickCollapseSidebar(event) {
    if(this.props.sidebar.isCollapsed) {
        this.props.actions.expandSidebar(this.props.sidebar)
    } else {
        this.props.actions.collapseSidebar(this.state.sidebar)
    }
}

And I want to know if this is correct approach how to handle those kind of situations with Redux.

I know that I can use local state with react's "setState" method or use library as redux-ui to handle those situation, but i would like to do it with redux only.

My reducer for those actions is..

export default function sidebarReducer(state = [], action) {
switch (action.type) {
    case types.COLLAPSE_SIDEBAR:
        return Object.assign({}, state, {isCollapsed: true})
    case types.EXPAND_SIDEBAR:
        return Object.assign({}, state, {isCollapsed: false})
    default:
        return state
 }
}

Aucun commentaire:

Enregistrer un commentaire