0

I have two buttons (icons). Depending on which one I click (parameter), a function should be called to change my view layout.

export default class ToolbarPictograms extends Component {
      static propTypes = {
        layout: PropTypes.string.isRequired,
        changeLayout: PropTypes.func.isRequired
      }

      constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
      }

      handleClick = value => {
        this.props.changeLayout(value)
      }

      render() {
        const changeLayout = this.props.changeLayout
        return (
          <div style={style.container}>
            <Divider />
            <div className='row end-xs'>
              <ViewListIcon onClick={() => changeLayout('list')} />
              <ViewModuleIcon onClick={() => changeLayout('modules')}/>
            </div>
            <Divider />
          </div>
        )
      }
    }

Currently I use arrow functions, it works but I have a warning: JSX props should not use arrow functions

What is the best way to do something like this in React?

1 Answer 1

1

The recommended way to do this is to pass a reference to the function as a property of the subcomponents, and then have the subcomponents invoke the function with the required arguments. The reason for doing it this way is that creating functions during rendering can lead to performance problems due to increased garbage collector activity.

So, you would change your function to

render() {
        const changeLayout = this.props.changeLayout
        return (
          <div style={style.container}>
            <Divider />
            <div className='row end-xs'>
              <ViewListIcon onClick={this.props.changeLayout} />
              <ViewModuleIcon onClick={this.props.changeLayout}/>
            </div>
            <Divider />
          </div>
        )
      }

Then, in ViewListIcon and ViewModuleIcon, invoke the callbacks with appropriate arguments. These could be hard coded or passed in as more props.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.