What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet:

<ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider>

The <Layout> component includes more nested components.

Further down in my code, I have a class that looks like this:

import React from 'react';

export default React.createClass({
  render: function(){
    var classes = [
      'js-select-product',
      'pseudo-link'
    ];

    if (this.props.selected) {
      classes.push('bold');
    }

    return (
      <li className="js-product-selection">
        <span onClick={this.props.onClick} className={classes.join(' ')} data-product={this.props.id}>{this.props.name}</span>
      </li>
    );
  }
});

Instead of using this.props.onClick, I would like to dispatch an event to update the state in a reducer. I've come across some information online regarding context but there seems to be conflicting opinions on whether or not it is being deprecated.

EDIT I have found mention of this connect method, but I recall reading advice against using connect in child components.

Answer №1

Instead of focusing too much on children components, a better approach is to organize your app with connected and non-connected components. Non-connected components should be stateless, pure functions that receive all necessary data through props. Connected components, on the other hand, should utilize the connect function to link redux state and dispatcher to props, and then handle passing these props down to child components.

Your application may have numerous connected and non-connected components. For further insight into this design pattern, you can refer to this article (authored by the creator of redux), which delves deeper into the roles of non-connected (dumb) components for UI display and connected (smart) components for component composition.

Consider the following example (using newer syntax):

class Image extends React {
  render() {
    return (
      <div>
        <h1>{this.props.name}</h1>
        <img src={this.props.src} />
        <button onClick={this.props.onClick}>Click me</button>
      </div>
    );
  }
}

class ImageList extends React {
  render() {
    return (
      this.props.images.map(i => <Image name={i.name} src={i.src} onClick={this.props.updateImage} />)
    );
  }
}

const mapStateToProps = (state) => {
  return {
    images: state.images,
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    updateImage: () => dispatch(updateImageAction()),
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageList);

In this scenario, ImageList functions as a connected component while Image serves as a non-connected component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React application experiencing continuous SpeechRecognition API without stopping

I need assistance with integrating speech recognition into my web application using Web API's speech recognition feature. Below is the React code I am currently working with: import logo from './logo.svg'; import './App.css'; impor ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

What is the significance of the term "Object object"?

I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick) is clicked. There are [Object object] elements in the array. The last line ...

Ways to conceal the scroll bar upon the initial loading of a webpage

Recently, I created a single-page website consisting of 4 sections. The client has specific requirements that need to be fulfilled: The scrollbar should not be visible when the page loads. Once the user starts scrolling past the second section, the scrol ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

When attempting to open a popup form by clicking a button, the code fails to function on IE6

Everything seems to be running smoothly on Firefox, however I am encountering issues with Internet Explorer 6. Here is a snippet of the problematic code: document.getElementById('layout').style.opacity = .7 document.getElementById('layout&a ...

What is the best way to activate an input field in react-select?

Currently, I am working on a dropdown feature using react-select and have encountered some issues that need to be addressed: 1) The input field should be focused in just one click (currently it requires 2 clicks). 2) When the dropdown is opened and a cha ...

The error message "ReferenceError: express is not defined" indicates that Node.js is

Recently, I started using Nodejs to develop web servers, utilizing the express module. To install it, I used the command: "sudo npm install -g express". However, upon running the program, an error occurred: "ReferenceError: express is not defined ...

Conceal or reveal input elements with a toggle function in jQuery by utilizing

When the user chooses an option from a dropdown list, I want to display or hide different input fields accordingly. I attempted to use toggle with boolean values, but it doesn't seem to be working as expected. I expect that if I send 'true' ...

Is it possible for jQuery UI Tabs to load entire new HTML pages?

In my index.html file, I have set up 3 different tabs. Using the jQuery UI function tabs(), I am attempting to load an HTML page via Ajax. Each HTML page includes the jQuery library and contains the following code: <link type="text/css" href="css/redmo ...

Error in NVD3 causing charts to be inaccurately rendered

While utilizing a stacked area chart in the Stacked display mode, there appears to be an issue with the shading under the graph, particularly on the left side of the displayed plot below. We are currently working with d3 v3.4.9 and nvd3 v1.1.15b. Do you ...

I understand the reason behind the unexpected { token error, but I'm unsure of how to resolve it when my PHP script needs to transmit a collection of data to JavaScript

I am currently utilizing this JavaScript fetch code to retrieve data from PHP async sendRequest(selectValue=this.selectValue){ const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue); const fetchJSON = await fe ...

Incorporating Only XSD Files into an HTML Input Tag: A Simple Guide

Is there a way to restrict a file input element to only display XSD files? I attempted the following: <input type="file" accept="text/xsd" > Unfortunately, this method is not working as it still allows all file formats to be disp ...

What is the purpose of implementing asynchronous loading for JavaScript in my webpack setup?

I am facing difficulties with handling unusual codes. I am trying to add some query parameters using $.ajaxPrefilter in all jQuery ajax requests. I came across the following code snippet which seems to ensure synchronous loading order, but in my entry.js ...

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

Using RxJS v5 for Sending a POST Request with Parameters

Snippet of my RxJS code: .mergeMap(action => { const user = store.getState().user; return ajax.post(`${config.API_BASE_URL}/api/v1/rsvps`, { rsvp: { meetup_id: action.payload, user_id: user.id, } }) .map(action => calenda ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Display the Add button in the React Material-UI autocomplete when there are zero search results available

Is there a method to display an "Add" button when no results are found? How can I receive an event notification when no options are available? I have noticed the existence of the noOptionsText prop, but I am unable to determine how to trigger an event in c ...