简体   繁体   中英

React JSX selectively pass attribute to component

This code works but I cannot help but think there's a better way of doing it. I cannot set expanded to false because the component breaks when I do (like they do in Set JSX attribute based on another JSX attribute react )

Also, I need to add more condition branches and it will mean duplication of code

if (itemProps.Expanded == true) {
  return (
    <Accordion expanded={true}>
    ...
    </Accordion >
  )
}
else {
  return (
    <Accordion>
    ...
    </ Accordion>
  )
}

Any suggestions?

You can create props object dynamically and pass the props with ...(spread)

const props = itemProps.Expanded == true ? { expanded: true } : {};
return <Accordion {...props}>...</Accordion>;

Sorry guys tried this and it worked. Thank you for your time

let expanded = undefined;
if (itemProps.Expanded) {
  expanded = true;
}

return (
    <Accordion expanded={expanded}>
    ...
    </Accordion >
)
```

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