简体   繁体   中英

How to render jsx in react with condition true and array mapping?

I want to render a JSX with some condition being true and map through an array.

below is the code,

{this.props.variables &&
     this.props.variable.map((variable, index) => {
         let element;
         if (variable.anchor) {
             element = document.querySelector(variable.anchor);
         }
         this.box_ref.current && element && (// error here
             <Childcomponent
                 element1={this.box_ref.current}
                 anchor={variable.anchor}
              />)
          }
      }
  )
}

There is an error saying that the expression is not an assignment or a call. how can I fix it? thanks.

You need to provide a return value for #Array.map callback .

Also, you should provide unique keys to React elements within an array:

<>
  {this.props.variables &&
    this.props.variable.map((variable, index) => {
      let element;
      if (variable.anchor) {
        element = document.querySelector(variable.anchor);
      }
//       v Add return statement
      return (
        this.box_ref.current &&
        element && (
          <Childcomponent
            key={index}
            element1={this.box_ref.current}
            anchor={variable.anchor}
          />
        )
      );
    })}
</>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM