inhwrbp
inhwrbp

Reputation: 619

How to organize actions that don't modify state?

let's say I have a react component like this:

class App extends Component {
  print = () => {
    const { url } = this.props
    const frame = document.createElement('iframe')

    frame.addEventListener('load', () => {
      const win = frame.contentWindow

      win.focus()
      win.print()
      win.addEventListener('focus', () => document.body.removeChild(frame))
    })

    Object.assign(frame.style, {
      visibility: 'hidden',
      position: 'fixed',
      right: 0,
      bottom: 0
    })

    frame.src = url

    document.body.appendChild(frame)
  }

}

Basically, clicking a button calls the print function in the browser for the user. In a situation like this, do I still make this into a redux action like DO_PRINT that doesn't actually do anything to my redux state or do I just not bother with it?

Upvotes: 1

Views: 81

Answers (1)

Alvin Teh
Alvin Teh

Reputation: 787

For your particular example, I would avoid creating a Redux action as there is no need for that DO_PRINT to update any state if it is only calling window.print().

In fact, assuming you're creating a "Print button" component, I would redefine this as a dumb component. (See differences between presentationl and container components.)

import React from ‘react’;

const PrintButton = () => {
  const onClick = () => {
    window.print();
  };

  return <button onClick={onClick}>Click Me</button>
};

export default PrintButton;

FYI, the code above might not be the most efficient way of declaring event handlers for stateless components as the function is potentilly called each time the component is rendered. There might be better (more efficient) ways (described in another SO question) but that's beyond this question.

Upvotes: 1

Related Questions