Search code examples
reactjsreduxdispatch

How to dispatch value onChange


I'm building a search component and I've set up my actions and reducers and so on... but I can't figure out how to dispatch an event in my component. What should be inside the onChangeValue attribute?

Here's the code:

import React from "react";
import { connect } from "react-redux";
import { getListOfUsers, clearDetails } from "../../actions/actions";
import SearchBar from "../../components/search/search";

const SearchBarContainer = onChangeValue => {
  return <SearchBar onChangeValue={onChangeValue} id="search" icon="search" />;
};

const mapStateToProps = state => {
  return {};
};

const mapDispatchToProps = dispatch => {
  return {
    onChangeValue: e => {
      dispatch(getListOfUsers(e.target.value));
      dispatch(clearDetails());
    }
  };
};

const connected = connect(
  mapStateToProps,
  mapDispatchToProps
)(SearchBarContainer);

export default connected;

Solution

  • SearchBarContainer is a functional component and hence it won't have state or this variable. You need to get them from the props. Also dispatch function onChangeValue is available as a prop to the container.

    const SearchBarContainer = ({ onChangeValue, value }) => {
      return (
        <SearchBar
          onChangeValue={onChangeValue}
          value={value}
          id="search"
          icon="search"
        />
      );
    };