-3

Is there a way I can shorten this?

const visitInfo = (date, guide, attendee) => {
  return (
    <>
      {(date || guide) && ' The tour was performed'}
      {date && ' at '}
      {date && <TimeFormat>{date}</TimeFormat>}
      {date && ' on '}
      {date && <DateFormat}>{date}</DateFormat>}
      {guide && ` by ${guide}`}
      {attendee && ` and was attended by ${attendee}`}.
    </>
  )
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user3378165
  • 6,546
  • 17
  • 62
  • 101
  • 1
    ...did you *try* anything? It feels like `date &&` could stand to be factored out if nothing else. – jonrsharpe Sep 02 '20 at 19:05
  • @jonrsharpe Yes, I spent long time to figure out to avoid the `date &&` repetition but couldn't find another solution than the one above and that's why I have posted the question. Does this look like I haven't tried anything? – user3378165 Sep 02 '20 at 19:34
  • 1
    You don't *mention* trying any other things, that's all we can go on. Also it doesn't seem very conventional; is visitInfo supposed to be a function-based component? Do DateFormat and TimeFormat really take the date as a *child*? – jonrsharpe Sep 02 '20 at 20:04
  • Does this answer your question? [Is there a way to render multiple React components in the React.render() function?](https://stackoverflow.com/questions/32577886/is-there-a-way-to-render-multiple-react-components-in-the-react-render-functio) – Emile Bergeron Sep 02 '20 at 20:06
  • @jonrsharpe Thanks for your feedback, much appreciated, I'm happy to learn. – user3378165 Sep 02 '20 at 20:13

2 Answers2

3

Text and other elements both count as children of an element, so you can wrap them in a fragment too, letting you factor out the repetition of date &&:

const visitInfo = (date, guide, attendee) => {
  return (
    <>
      {(date || guide) && ' The tour was performed'}
      {date && (
        <> at <TimeFormat>{date}</TimeFormat> on <DateFormat>{date}</DateFormat></>
      )}
      {guide && ` by ${guide}`}
      {attendee && ` and was attended by ${attendee}`}.
    </>
  );
}

The formatter here seems unhappy, but it works fine in e.g. Babel's REPL.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0
const visitInfo = (date, guide, attendee) => {
  return (
    <>
      {(date || guide) && ' The tour was performed'}
      {date && ` at ${<TimeFormat>{date}</TimeFormat>} on ${<DateFormat>{date}</DateFormat>}`}
      {guide && ` by ${guide}`}
      {attendee && ` and was attended by ${attendee}`}.
    </>
  )
}
arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60