Redux: Where to place "dumb" handlers? - reactjs

Let's say I have a component with a click handler that doesn't need to modify the Redux store. i.e. it might, depending on the props of the component, initiate a download of a file.
i.e. you have an web interface for a list of videos that are processing on the server. Click on a video item checks the props to see if the video has finished processing. If it has, it'll start downloading the video, other it'll pop up an alert explaining that the video is still processing.
Usually, handlers tend to be defined in mapDispatchToProps. However, in this case, I don't actually need to touch the state, so defining the handler in there doesn't feel correct.
Would the correct place for such a handler be in the 'dumb' component rather than the 'smart' container?

I would still have this in the container and pass the function down as a prop -- just not in mapDispatchToProps.
e.g:
// SmartComponent.js
import React, { Component } from 'react'
import DumbComponent from '/path/to/DumbComponent'
export class SmartComponent extends React.Component {
constructor(props) {
super(props);
this.handleOnClick = this.handleOnClick.bind(this);
}
handleOnClick(params) {
// do whatever you need to do here
}
render() {
return (
<DumbComponent handleOnClick={this.handleOnClick} />
);
}
};
export default SmartComponent;
// DumbComponent.js
import React from 'react'
import Button from '/path/to/button'
export const DumbComponent = (props) = {
const { handleOnClick } = props;
return (
<Button onClick={handleOnClick} />
);
}
export default DumbComponent;
I should probably also add that I usually structure it so that I have another level above this which is connected to the store - something like ContainerComponent for example - which is usually the view for the route. This is why I have not connected this SmartComponent to the store. You could do that though.

Related

Does Redux update the React component it is connected to automatically?

I was under the impression that when my Redux store gets updated (via dispatching an action to the reducer), my Provider should make the new store available to all it's child components. So when I connect a container component to the store by using mapStateToProps(), that component should re-render when it receives the new props that go along with the store being updated, without the need for componentWillReceiveProps(). Am I wrong in thinking that?
After several hours of reading docs and other stack overflow answers, something just isn't clicking for me. I'm pretty sure my reducer is working correctly and is returning a new object, my components have access to the store, and my initial state is rendering just fine. If anyone could give me a better idea about the flow of things, I would be forever grateful.
Basically, I have a header component that imports the store, uses Provider and renders a "FAQ" component:
import React from 'react';
import FAQ from './Faq';
import {Provider} from "react-redux";
import store from '../store/index'
class Header extends React.Component {
render() {
return (
<Provider store = {store}>
<FAQ />
</Provider>
)
}
}
export default Header;
The "FAQ" component is a container that is connected to the store via mapStateToProps(), it imports the "FAQTest" component, which is a presentational component that will get passed this.state.thisFood as props so that it can render the data from the store. There is also an "addFood" function that dispatches my action, which can be seen in mapDispatchToProps() at the bottom.
import React from 'react';
import {connect} from 'react-redux';
import FAQTest from './faqTest';
class FAQ extends React.Component {
constructor(props) {
super(props);
this.state = {
thisFood: props.breakfast
};
}
//adding this makes the component state update, but I think it should work without it
componentWillReceiveProps(nextProps){
this.setState({thisFood: nextProps.breakfast})
}
addFood = () => {
this.props.addFood();
}
render() {
return (
<React.Fragment>
<button onClick={this.addFood}> Add Food </button>
<FAQTest food = {this.state.thisFood} />
</React.Fragment>
)
}
}
const mapStateToProps = function(state) {
return {
breakfast: state.faq.breakfast
}
}
function mapDispatchToProps(dispatch) {
return {
addFood: () => dispatch({type: 'ADD_FOOD', food: 'Waffles'})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(FAQ);
When I click the "Add Food" button, my store gets updated, and the props of my FAQ container component get updated, because of mapStateToProps(). I thought this would trigger my FAQ component to update its state, however the state does not get updated unless I use componentWillReceiveProps. Is this working as expected?
Just in case I'm doing something silly, here is my reducer:
const initialState = {
breakfast: ["eggs", "bacon"]
}
export default function faqReducer(state = initialState, action) {
switch (action.type) {
case "ADD_FOOD":
return Object.assign({}, state, {
breakfast: [...state.breakfast, action.food]
})
default:
return state;
}
}
Here is my root reducer with my combineReducers() function:
import { combineReducers } from "redux";
import faq from './faqReducer'
export default combineReducers({
faq: faq
});
The problem is that you're copying data from props to state, but only doing that when the component is mounted, and then expecting the state to somehow be updated when new props arrive.
Copying data from props to state is almost always the wrong approach. Please don't do that. Just use the value from props.
Two additional suggestions for improving the code:
Prefer using the "object shorthand" form of mapDispatch, rather than writing it as a function
We recommend using our new official Redux Starter Kit package as the standard way to write your Redux logic. It includes utilities to simplify several common Redux use cases, including store setup, defining reducers, immutable update logic, and even creating entire "slices" of state at once.

React.js - how to pass event handlers to deeply nested component without props drilling?

I have the structure of components (nested) that seems like this:
Container
ComponentA
ComponentB
ComponentC(want to handle event here with state that lives on container)
Do I need to pass as props all the way from Container, ComponentA, ComponentB and finally ComponentC to have this handler? Or is there another way like using Context API?
I'm finding a bit hard to handle events with react.js vs vue.js/angular.js because of this.
I would recommend using either Context API (as you mentioned) or Higher Order Components (HoC)
Context Api is your data center. You put all the data and click events that your application needs here and then with "Consumer" method you fetch them in any component regardless of how nested it is. Here is a basic example:
context.js //in your src folder.
import React, { Component, createContext } from "react";
import { storeProducts } from "./data"; //imported the data from data.js
const ProductContext = createContext(); //created context object
class ProductProvider extends Component {
state = {
products: storeProducts,
};
render() {
return (
<ProductContext.Provider
//we pass the data via value prop. anything here is accessible
value={{
...this.state,
addToCart: this.addToCart //I wont use this in the example because it would
be very long code, I wanna show you that, we pass data and event handlers here!
}}
>
// allows all the components access the data provided here
{this.props.children},
</ProductContext.Provider>
);
}
}
const ProductConsumer = ProductContext.Consumer;
export { ProductProvider, ProductConsumer };
Now we set up our data center with .Consumer and .Provider methods so we can access
here via "ProductConsumer" in our components. Let's say you want to display all your products in your home page.
ProductList.js
import React, { Component } from "react";
import Product from "./Product";
import { ProductConsumer } from "../context";
class ProductList extends Component {
render() {
return (
<React.Fragment>
<div className="container">
<div className="row">
<ProductConsumer>
//we fetch data here, pass the value as an argument of the function
{value => {
return value.products.map(product => {
return <Product key={product.id} />;
});
}}
</ProductConsumer>
</div>
</div>
</React.Fragment>
);
}
}
export default ProductList;
This is the logic behind the Context Api. It sounds scary but if you know the logic it is very simple. Instead of creating your data and events handlers inside of each component and prop drilling which is a big headache, just put data and your event handlers here and orchestrate them.
I hope it helps.

React-Redux: how can i get store data when component first mounts

I've got api data saved in redux store that I use with a few different components. I am trying to figure out a way to access this store data when a new component is first mounted and the data is already in store.
I can't really pass in as a prop because the components are not children. I've considered triggering a MapStateToProps event but that doesn't seem like the correct way. I could call the api again but that doesn't make sense.
Instead of rendering a component you can use a "smart component" and render it:
import React, { PureComponent } from 'react';
import RPT from 'prop-types';
import { connect } from 'react-redux';
const mapStateToProps = state => ({
name: state.user.name
});
class WelcomeMessage extends PureComponent {
static propTypes = {
name: RPT.string.isRequired;
}
render() {
const { name } = this.props;
return (
<h2>
{`Welcome, ${name}`}
</h2>
);
}
}
export default connect(mapStateToProps)(WelcomeMessage);
So in this way your component will always be connected to your store no matter where is located.
Recommended lecture: Difference between smart and dumb components in React.

Reusing container and container extending other containers

import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { setLocation } from 'redux/modules/filters'
import SearchForm from 'components/SearchForm/SearchForm'
type Props = {
};
export class HomeSearchContainer extends React.Component {
props: Props;
static contextTypes = {
router: React.PropTypes.object.isRequired
};
constructor(props) {
super(props)
this.onSearch = this.onSearch.bind(this)
}
onSearch(address, event) {
event.preventDefault()
if (address) {
this.props.actions.setLocation(address)
}
this.context.router.push('/browse_items')
}
render() {
return (
<SearchForm
onSearch={this.onSearch}
currentLocation={this.props.currentLocation}
/>
)
}
}
const mapStateToProps = (state) => {
return {
currentLocation: state.filters.location
}
}
const mapDispatchToProps = (dispatch) => {
var actions = {
setLocation
}
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomeSearchContainer)
I have a few questions to validate my understanding.
Do we ever re-use containers? Am I correct if I say we intend to re-use components but not containers?
In the above code, I want to create another container that doesn't redirect to /browse_items. In other words, I just want to override onSearch function of this container. Is it okay to extend this container?
First of all, in my mind a container is a certain kind of component, so following this article: https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.jqwffnfup I'll rather talk about container components and presentational components.
Ad 1) I would say we can re-use container components as well as presentational components - this always depends on how our code is structured. E.g. a container component might have child components, which can be different in different parts of the screen, but the container component is being re-used.
Ad 2) If you just want to have a different onSearch functionality, I might consider passing the onSearch callback to the HomeSearchContainer via the props. That way, you can re-use the same container, but it behaves differently.
Looking closely at your code, there is then not much left to the HomeSearchContainer, so you might as well use the SearchForm directly. If you need the SearchForm in multiple places, it might be worth pulling out the onSearch function into its own file and re-using that. But this is hard to judge without seeing the rest of the application. So I'm trying to throw some ideas at you here, which may or may not apply to your codebase.

Initialize component with Async data

I'm trying to figure out how and where to load the data (ie call dispatch on my action) for my select box in react + redux + thunk. I'm not sure if it should go in the constructor of my App container, or should i load it inside my component (in my example: "MyDropdown")
My main App:
import MyDropdown from '../components/mydropdown';
// Should i import my action here and then...
// import { loadData } from '../actions';
class App extends Component {
render() {
return (
<div className="page-content">
<div className="option-bar">
// SEND it as a PROP inside MyDropdown...
<MyDropdown />
</div>
</div>
);
}
}
export default App;
My Component
// OR.. Should i load it in my MyDropdown component here?
import { loadData } from '../actions';
class MyDropdown extends Component {
// If i load it here on load, how do i do it?
render() {
return(
<select>
{renderOptions()}
</select>
);
}
}
I've tried componentDidMount() inside my App class, but it didnt seem to work. It seems to make sense to put the initialize data and call to actions there as it'll be all centralized, instead of calling actions inside my child components. Also, i'll have multiple select boxes that need to be loaded on startup, so my App class might grow quite a bit, is that the correct way to do it? I'm not sure what the best practice is as i've only just started learning react.
You should separate data components from presentation components (see post here).
So in your small example, MyDropdown should be passed all the data it needs in order to render the component. That would mean fetching the data in App (or some parent component of the component actually rendering the view.
Since you're working with React and Redux, the react-redux library provides a helper function to generate containers that fetch the data required for your presentation component.
To do that, change App to:
import { connect } from 'react-redux'
import MyDropdown from '../components/mydropdown';
import { loadData } from '../actions';
// This class is not exported
class App extends Component {
componentDidMount() {
this.props.loadData()
}
render() {
return (
<div className="page-content">
<div className="option-bar">
<MyDropdown data={this.props.data}/>
</div>
</div>
);
}
}
function mapStateToProps(state) {
const { data } = state
return {
data
}
}
function mapDispatchToProps(dispatch) {
return {
loadData(){
dispatch(loadData())
}
}
}
// Export a container that wraps App
export default connect(mapStateToProps, mapDispatchToProps)(App);
Alternatively, you could keep App the same and change MyDropdown to:
import { connect } from 'react-redux'
import { loadData } from '../actions';
// Exporting this allows using only the presentational component
export class MyDropdown extends Component {
componentDidMount() {
this.props.loadData()
}
render() {
return(
<select>
{renderOptions(this.props.data)}
</select>
);
}
}
function mapStateToProps(state) {
const { data } = state
return {
data
}
}
function mapDispatchToProps(dispatch) {
return {
loadData(){
dispatch(loadData())
}
}
}
// By default, export the container that wraps the presentational component
export default connect(mapStateToProps, mapDispatchToProps)(MyDropdown);
In both cases, look at what is actually being exported as default at the end. It's not the component; it's the return of connect. That function wraps your presentational component and returns a container that is responsible for fetching the data and calling actions for the presentational component.
This gives you the separation you need and allows you to be flexible in how you use the presentation component. In either example, if you already have the data you need to render MyDropdown, you can just use the presentation component and skip the data fetch!
You can see a full example of this in the Redux docs here.

Resources