0

I was wondering if doing this is considered as a bad practice in the react world?

const renderComparisonScore = (score) => {
 return (
  <div>
   {score}
  </div>
 )
}
const Visualization = ({ score }) = {
 return (
  <div>
   {renderComparisonScore(score)}
  </div>
 )
}

As you can see I'm calling the function renderComparisonScore and passing the argument I know that the regular way of doing something like that is passing that as a prop like this:

const ComparisonScore = ({ score }) => {
 return (
  <div>
   {score}
  </div>
 )
}
const Visualization = ({ score }) => {
 return (
  <div>
   <ComparisonScore score={score} />
  </div>
 )
}

My question is, can I pass things in react as arguments instead of passing things using props, and if not why?

jean182
  • 3,213
  • 2
  • 16
  • 27
  • Does this answer your question? [React props: Should I pass the object or its properties? Does it make much difference?](https://stackoverflow.com/questions/52621169/react-props-should-i-pass-the-object-or-its-properties-does-it-make-much-diffe) – Arnab Roy Dec 11 '19 at 18:20
  • I think the bigger issue here is there isn't a clear separation of concerns going on. Separate out what is stateful and who needs to display it hence why I would lean towards the latter example – Oliver Dec 11 '19 at 18:25
  • no that is a different case, since is using props to pass the arguments. @ArnabRoy – jean182 Dec 11 '19 at 18:25
  • The biggest difference is that the first case (simple function), it's just a rendering helper, while in the second case, it's a completely different component which will appear in the React nodes tree and will have its own lifecycle. – Emile Bergeron Dec 11 '19 at 19:00
  • If you're planning to reuse `ComparisonScore`, make it a full component in its own file, etc. Otherwise, it may as well stay a simple helper function or a local variable like [Olivier suggests in his answer](https://stackoverflow.com/a/59292029/1218980). – Emile Bergeron Dec 11 '19 at 19:02

1 Answers1

2

My .02:

In larger applications if you run into a situation such as this (e.g where you need to map a bunch of data to build a view).

const MyComponent = props => {
  const cards = props.arrayOfData.map(el => (
    <div>Lots of view code and styling</div>
  ));

  // ...

  return (
    <div>
      [...other components]
      {cards}
    </div>
  );
};

This would be helpful to try and minimize the amount of content in any given components render to a more manageable amount.

Other than that case though, I would definitely just to stick to regular props as you want to keep some orderliness to stateful & logic based versus view

Oliver
  • 237
  • 2
  • 5