peter flanagan
peter flanagan

Reputation: 9830

alternative to using arrow function in render with same effect

I am using the react-custom-scrollbars library and am changing the zIndex and other css properties of the scrollbar.

This is working, however, I am getting warnings as I am using an arrow function in my render method. The library's documentation explains that to carry this out to use an arrow function in the render method. As you can see here there has been an issue raised for this, but this has not been updated in the documentation.

I am having difficulties understanding how to implement the following behavior without using arrow functions in render.

render(){

  <Scrollbars renderThumbVertical = {({
      style, ...props }) =>
       <div { ...props} style = {{
        ...style,
        backgroundColor: 'rgba(0, 0, 0, 0.2)',
        zIndex: 10000,
        borderRadius: 2
      }}/>
  }>
     <p>Content here</p>
     <p>Content here</p>
     <p>Content here</p>

   </Scrollbars>

}

Upvotes: 1

Views: 498

Answers (2)

Yozi
Yozi

Reputation: 12765

I recommend declare methods as a class property. Then the methods will be created only once. http://babeljs.io/blog/2015/06/07/react-on-es6-plus

class MyComponent extends React.Component {
    render(){
         return (
           <Scrollbars renderThumbVertical={this.renderThumbVertical}>
             <p>Content here</p>
             <p>Content here</p>
             <p>Content here</p>
           </Scrollbars>
        );
    }
    renderThumbVertical = () => {
         // code
    }
}

Upvotes: 0

madox2
madox2

Reputation: 51931

You can simply define render thumb function outside of render method and then pass it to props:

function renderThumbVertical({ style, ...props }) {
  return (
    <div { ...props} style = {{
      ...style,
      backgroundColor: 'rgba(0, 0, 0, 0.2)',
      zIndex: 10000,
      borderRadius: 2
    }}/>
  )
}

// and use it in component
render() {
  return (
    <Scrollbars renderThumbVertical={renderThumbVertical}>
       <p>Content here</p>
       <p>Content here</p>
       <p>Content here</p>
    </Scrollbars>
  )
}

Thumb renderer could also be an instance method. If so you can pass it as this.renderThumbVertical. However if you need to access this inside that method don't forget to bind it in constructor or use class properties.

Upvotes: 2

Related Questions