0

I have a question regarding the best way to do a render in react when using arrays. One way is to create functions which render the elements to be rendered and then call the functions to do the rendering. Other way is to just use the array.map to create the elements directly inside render. which way is better? I have heard that calling a function isn't the best way because it's slow and it creates a new instance of the element each time it is rerendered.

What do you guys think?

export default class Calculator extends React.Component {
  renderButtons = arr => {
    let btnArr = [];
    arr.map(item => {
      btnArr.push(<button>{item}</button>);
    });
    return btnArr;
  };
  render() {
    let keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let operations = ["+", "-", "*", "/"];
    return (
      <div>
        {keys.map(item => {
          return <button key={item}>{item}</button>;
        })}
        <div>{this.renderButtons(operations)}</div>
      </div>
    );
  }
}

One is for the keys array, where I have just directly run the map on it to render the number buttons

I have used the other method for the operations buttons where I have called a function to do the rendering.

I could have used the same way for the numbers also, but just want to know which method is better.

0

1 Answer 1

1

I prefer the style used for your buttons, because I don't like to see JavaScript code in my JSX.

However you're only halfway there. Your function name gives you a hint: renderButtons. You should "render the buttons" using render() in a separate component. I would create two new components: Button and ButtonList. ButtonList would import and use the Button component and your Calculator component would import and use the ButtonList.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually both numbers and operations are buttons. Which one do you like?
I still think the button and the button list should be extracted into their own components. The operator list can use the button list component too.
ah,yes. I do agree that they can be extracted into their own component. Correct, but my confusion was regarding calling function inside the render. is it really slower and creates many instances each time a rerender happens?
I would consider that premature optimization. Write clean code that other programmers can understand by putting things into separate components. When and if you run into a problem with performance, then cross that bridge when you get there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.