最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to conditionally add a group of props to a react component? - Stack Overflow

programmeradmin3浏览0评论

I have a group of props that I need to apply to a ponent only if a certain condition is met.
So I grouped the props in an object:

const props = {
  a: "",
  b: "",
};

And then tried to conditionally apply them to the ponent:

<div {condition && ...props}/>

But React doesn't seem to be allowing this, so is there another way?

I have a group of props that I need to apply to a ponent only if a certain condition is met.
So I grouped the props in an object:

const props = {
  a: "",
  b: "",
};

And then tried to conditionally apply them to the ponent:

<div {condition && ...props}/>

But React doesn't seem to be allowing this, so is there another way?

Share Improve this question edited Jun 14, 2021 at 4:17 Moaaz Bhnas asked Jun 13, 2021 at 11:46 Moaaz BhnasMoaaz Bhnas 1,1707 gold badges20 silver badges41 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 15

You should wrap your expression and then use the spread syntax on the result of that expression:

<div {...(condition && props)}></div>

Where props is an object like you described:

const props = {
  a: "",
  b: "",
};

When the condition is false, the && operator evaluates to false. As a result, React calls React.createElement(type, props, ...children) with a second argument of false, leaving the props untouched. When condition is true, the && evaluates to the props object, allowing you to merge your object's properties.

发布评论

评论列表(0)

  1. 暂无评论