Timon
Timon

Reputation: 68

React function or object

I wonder if it is fine to predefine some JSX and use it multiple times in different components.

const saveButton = 
  <div class="u-mth u-textRight">
    <Button variant="flatBlue">Save</Button>
  </div>;

const test = <div>{saveButton}</div>;

Is there any downside compared to a normal functional react component?

export const SaveButton = () => (
  <div class="u-mth u-textRight">
    <Button variant="flatBlue">Save</Button>
  </div>
);

const test = <div> <SaveButton /> </div>

And what about this one instead of functional with react props:

const saveButton = (text: string) => (
  <div class="u-mth u-textRight">
    <Button variant="flatBlue">{text}</Button>
  </div>
);

const test = <div> {saveButton(text)} </div>;

Upvotes: 2

Views: 928

Answers (3)

Bojan Golubovic
Bojan Golubovic

Reputation: 151

  1. It is just declaring variables. Nothing else. In this case, using ES6 and JSX.
  2. It is the same thing as 1. just as function. This function returns what you declared under 1. Using ES6. No downsides.
  3. The same as 2. with arguments object, actually passing parameter to function using ES6 and Type Script.

    function saveButton(props) { return <div class="u-mth u-textRight"> <Button variant="flatBlue">{props.text}</Button> </div>; } const element = <saveButton text="Save" />; ReactDOM.render( element, document.getElementById('root') );

This is the way using props and pure function.

Upvotes: 0

Yalamber
Yalamber

Reputation: 7580

First one is simply just jsx, it's not a component.

Second one is a stateless component, which is fine as well but you have not used any props.

Third one is also just a function not a component as you have not used props. What I would do is as @estus recommended in answer.

But please also view this link which says they way you have approached is actually faster.

Upvotes: 4

Estus Flask
Estus Flask

Reputation: 222493

React component (snippet 2) will appear as in React devtools as <SaveButton>...</SaveButton>, while other options won't.

React component (snippet 2) is the way it's usually done. If a component needs to expose dynamic behaviour, parameters should be passed as props:

const SaveButton = ({ text }) => (
  <div class="u-mth u-textRight">
    <Button variant="flatBlue">{text}</Button>
  </div>
);

and

<SaveButton text={text} />

Helper function (snippet 3) is the way how the performance of React component can be improved, by calling it directly. It can be considered preliminary optimization, unless proven otherwise.

As long as element hierarchy doesn't expose dynamic behaviour, the definition of React elements as a variable (snippet 1) has no downside under normal circumstances. If there's a possibility that dynamic behaviour can be necessary in future (custom or localized text), it will require refactoring.

Upvotes: 2

Related Questions