Ad

React Carousel RenderArrow Consts Is Not Defined

- 1 answer

I'm using react-elastic-carousel and i am trying to render my own custom arrows.
This is my code (taken from an example in the docs)

function App() {
  return (
    <div>
      <Carousel
        renderArrow={({ type, onClick }) => {
          const pointer = type === consts.PREV ? '👈' : '👉'
          return <button onClick={onClick}>{pointer}</button>
        }}
      >
        <Item>1</Item>
        <Item>2</Item>
        <Item>3</Item>
        <Item>4</Item>
        <Item>5</Item>
        <Item>6</Item>
      </Carousel>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I'm getting the error:

consts is not defined

I have 2 questions here:
1. What is this consts variable and how can i define it?
2. What is this style of code, why do we need to pass a function and not just a component to renderArrow?

Ad

Answer

What is this consts variable and how can i define it?

In the source code it's this file, and you can import it like this:

import { consts } from 'react-elastic-carousel';

Or to import both the carousel and the consts:

import Carousel, { consts } from 'react-elastic-carousel';

What is this style of code, why do we need to pass a function and not just a component to renderArrow?

It's called a "render prop", and it's more flexible than just passing in a reference to a component. If all you passed in was a component, then they would have to guess what you wanted them to do with type and onClick, and so the best they could do would be to just pass them both in as props to your component.

With a function, then will call the function and hand you the props. You then decide what to do with them, and then return components that do what you want. If all you want to do is put those props onto a component, you can:

renderArrow={props => <button {...props}/>}

But you can also do more complicated things

Ad
source: stackoverflow.com
Ad