I am studying Redux but I'm having problems to understand it properly. Now I am building a personal project with it to learn it.
I have this "Settings button" (actually, it is a list item) on the navbar. When I click it, I want that another component shows itself. This will be the <Settings />
component. This component has a "Close button" to hide.
My idea is to have a property on the redux global store like this: settingsOpen: false
and when I click on the button it becomes true and the component appears and vice-versa. The close button always set the property equal to false and close the component.
Here you can find all the code: https://github.com/lbluigi/react-ecommerce
Anyway, I think the important parts are:
Header.js component
This is the list item clicked that would toggle the Settings component.
<a onClick={(event) => this.props.toggleSettings(event)} href="#settings" className="nav-link"><i className="fa fa-cog" aria-hidden="true"></i> Settings</a>
Settings.js component
This is the component that had to appear and disappear depending on the settingsOpens
property.
<div className={this.props.settings.settingsOpen ? 'settings' : 'hidden'}>
<i className="fa fa-times fa-3x" aria-hidden="true"></i>
{/* just a test <h2>{this.props.settings.themeColor}</h2> */}
</div>
toggleSettings.js action This is the function triggered by the click event on the settings button that I wrote before.
event.preventDefault();
return {
type: 'SETTINGS_TOGGLED'
}
settingsReducer.js reducer
This is the reducer that sets the initial properties that the user can change interacting with the Settings component.
{
settingsOpen: false,
themeColor: 'light',
gridView: 'grid'
}
I could write a lot more, but you will find everything on the GitHub repo that I linked before. I don't know how to proceed to change the property settingsOpen
on click.
Your settingsReducer
must be a function which returns an object (state) by dispatching actions. In your case it should be:
const defaultSettings = {settingsOpen: false, themeColor: 'light'}
const settingsReducer = (state = defaultSettings, action) {
if (action.type === 'SETTINGS_TOGGLED') {
return {
...state,
settingsOpen: !state.settingsOpen
}
}
return state
}