Elchy
Elchy

Reputation: 191

How can i pass parameter in Reactjs

How can i pass this.state.posts.length to items in React.js so i can get a dynamic number instead of 1, find below my variables.

const notEnough = {
  Larga: {
    breakpoint: { max: 4000, min: 0 },
    items: 1
  }
};

I have a condition in responsive props, if the lenght of posts is < 5, i need to pass the this.state.posts.length value to items.

responsive={this.state.posts.length < 5 ? notEnough : responsive}

Upvotes: 1

Views: 148

Answers (2)

Dupocas
Dupocas

Reputation: 21297

Right now notEnough is an object, you can turn it into a function which takes some parameters (posts.length) and returns an object.

const notEnough = items =>({
  Larga: {
    breakpoint: { max: 4000, min: 0 },
    items
  })
};

responsive={this.state.posts.length < 5 ? notEnough(this.state.posts.length) : responsive}

If notEnought is declared inside your component you don't really need to do that

const notEnough = {
  Larga: {
    breakpoint: { max: 4000, min: 0 },
    items: this.state.posts.length
  }
};

Upvotes: 1

Chris B.
Chris B.

Reputation: 5763

Seems to me like you're adding an unnecessary intermediary step. If you want 2 different variables to depend on the same condition, you can just insert the same condition in both places, assuming you're declaring this const somewhere it will respond to state changes:

const notEnough = {
  Larga: {
    breakpoint: { max: 4000, min: 0 },
    items: this.state.posts.length < 5 ? this.state.posts.length : 1;
  }
};

Upvotes: 0

Related Questions