React - Redux App : Handle Events in Stateless Components

react event target
how to call a component on button click in react
react stateless component event handler
react button onclick link
stateless component react example
addeventlistener react
react onclick
onpress in functional component

I asked same question with different form before but haven't reached proper solution yet. I want to avoid refreshing page when I delete data and define it with stateless component. There is my sample code:

BookListElement.js

import React from 'react';
import { connect } from 'react-redux';
import BookList from '../components/bookList';
import { deleteBook } from '../store/actions/projectActions';

const BookListElement = ({books, deleteBook}) => {
  if(!books.length) {
    return (
      <div>
        No Books
      </div>
    )
  }
  return (
    <div>
      {Array.isArray(books) ? books.map(book => {
        return (
          <BookList book={book} deleteBook={deleteBook} key={book._id} />
        );
      }): <h1>something wrong.</h1>}
    </div>
  );
};

const mapStateToProps = state => {
  return {
    books: state.books
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deleteBook: _id => {
      dispatch(deleteBook(_id));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement);

bookList.js

import React from 'react';

const styles = {
  borderBottom: '2px solid #eee',
  background: '#fafafa',
  margin: '.75rem auto',
  padding: '.6rem 1rem',
  maxWidth: '500px',
  borderRadius: '7px'
};

const BookList = ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  const handleClick = (e) => {
    e.preventDefault();
    deleteBook(_id);
  }
  return (
        <form>
      <div className="collection-item" style={styles} key={_id}>
        <h2>{author}</h2>
        <p>{publication}</p>
        <p>{publisher}</p>
        <button className="btn waves-effect waves-light" onClick={handleClick}>
          <i className="large material-icons">delete_forever</i>
        </button>
      </div>
    </form>
  );
};

export default BookList;

action.js

export const deleteBookSuccess = _id => {
  return {
    type: DELETE_BOOK,
    payload: {
      _id
    }
  }
};

export const deleteBook = _id => {
  return (dispatch) => {
    return axios.delete(`${apiUrl}/${_id}`)
      .then(response => {
        dispatch(deleteBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

reducer.js

const projectReducer = (state = [], action) => {
    case DELETE_BOOK:
          let afterDelete = state.filter(book => {
            return book._id !== action.payload._id
          });
          return afterDelete;
}

As you can see, I defined handleClick into onClick over bookList.js and page still needs to refresh after deleting data. How should I overcome that issue properly as a junior ?

I think the problem is you haven't set a type for <button>. For most browsers, if no type is specified it's set to <button type='submit'>.

Set it to <button type='button'> inside your BookList to avoid submitting the form.

Hi there, I'm working on an app where the root component contains the app state and the main This seems similar to what you get with React + Redux in JS. Proper way to handle events within stateless components? The chat window is the MatchingWindow component, which needs a chatid as its props to render the corresponding chat history between 2 users. I am sure that my Redux actions work fine but got problems when passing the updated Redux state to my React components. Below are 2 approaches that I tried:

The issue is that the native <form> submit event is still happening causing the page to refresh on button click. Try the following to prevent the native form by targeting the onSubmit event on the <form> element. This which would allow you to preventDefault() on the submit event.

// ...

const BookList = ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  const handleSubmit = (e) => {
    e.preventDefault();
    deleteBook(_id);
  }
  return (
     <form onSubmit={handleSubmit}>
      <div className="collection-item" style={styles} key={_id}>
        <h2>{author}</h2>
        <p>{publication}</p>
        <p>{publisher}</p>
        <button type="submit" className="btn waves-effect waves-light">
          <i className="large material-icons">delete_forever</i>
        </button>
      </div>
    </form>
  );
};

export default BookList;

Note: with the onSubmit on the <form> element, you need to remove onClick from the button. With <button type="submit", clicking the button will cause a form submit event to occur which would be handled in handleSubmit.

Update:

Given you are using React Router, you need to make sure you are using withRouter for Redux Integration. Try wrappping your BookListElement with the withRouter higher order component. This is assuming you are using react-router-dom:

import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import BookList from '../components/bookList';
import { deleteBook } from '../store/actions/projectActions';

// ...

export default withRouter(connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement));

Hopefully that helps!

Handling events with React elements is very similar to handling events on DOM elements. For example, this Toggle component renders a button that lets the user toggle This syntax is enabled by default in Create React App. SyntheticEvent · Test Utilities · Test Renderer · JS Environment Requirements · Glossary. State in React is just an object that lives within a component to keep track of changing data in that component. The change could be as a result of user interactions like clicking a button or

Your React code works as expected: https://glitch.com/edit/#!/so-52794886

If the Book List doesn't update after deleting one of the book, it might be that the _id returned from the server is of type string and _ids in the redux store are of type number, so filter predicate never matches and the item is never deleted from the list.

You can write Redux apps with React, Angular, Ember, jQuery, or vanilla JavaScript. We write functional stateless components unless we need to use local state Then, head straight to the advanced tutorial to learn how to handle network  Since Redux's principle is not to mutate the state, so calling ReactDom.render each time with a new state (in contrast to using this.setState({}) insides a React Component) is a better fit with the concept or principle of immutability? The other advantage is that the app can be written without using this, without class nor extends, all pure

FSC is a valid React component because it accepts a single “props” object We call such components “functional” because they are literally Event Handler in FSC in Javascript, React and Node.js. https://www.linkedin.com/in/waheng A button that says 'Download on the App Store', and if clicked it. EDIT: You now can with React Hooks. See the answer by Ante Gulin. You can't access React like methods (like componentDidMount, componentWillReceiveProps, etc) on stateless components, including refs. Checkout this discussion on GH for the full convo. The idea of stateless is that there isn't an instance created for it (state).

</button> ); } export default App;. App.js (Functional Component). import React from 'react'; function App() { function sayHello() { alert('Hello!')  Performance Finally, stateless functional components may soon offer improved performance as well. Since there’s no state or lifecycle methods to worry about, the React team plans to avoid unnecessary checks and memory allocations in future releases. Update: With React 16.6+, you can declare “pure” functional components via React.memo. And with Hooks in 16.7, functional components transpile smaller too.

Question: Redux + React with only stateless functions #1176 someValue} </div​> } function Child2(props) { function handleClick(event) { props.dispatch({ type: '​SOME_ACTION' I have been running an app for 1.5 years in production. Grabbing a snapshot of the state to deal with problems has become  11 Comments → State of React #1: A Stateless React App?. MaxArt August 1, 2016 at 5:14 am. That’s intresting, I ws wondering the same thing too. Why having a second layer of data when everything can be passed forth and back through properties?

Comments
  • In your condensed snippet of projectReducer, your switch statement is is switching on action.type right? Also, you are sure that response.data in action creator deleteBook is just the _id value? It's not nested inside an object property? It's not something like { _id: "123" }?
  • Yes, you're right. Its all set properly as you said.
  • Sorry can you clarify "its all set properly as you said."? If you log afterDelete in your reducer, can see you the difference in array length, as in the deleted item no longer being in the array?
  • Switching statement through action.type and I can see the difference in array when I delete data. Might be wrong define route parameter ?
  • See my updated answer, try wrapping connected BookListElement with withRouter from react-router-dom.
  • Did it but still needs to refresh.
  • You mean the page is still refreshing or you need to refresh the page for the list to update?
  • When I trigger button to delete data, I've to refresh the page to see update with onClick={handleSubmit} define.
  • You need to provide more explanation of what you mean.
  • You need to share your actions and reducers. It means you may not be updating your state correctly on dispatch of the action.
  • Added action.js and reducer.js
  • Thanks for contribution. I checked the type of _id over both side ( api and redux-store ) and each of them matches properly but I'll look into your sample to what I've missed or defined improper way.