user6642297
user6642297

Reputation: 393

Can a React function be changed into a class component

Please check the answer in the following link by Guilherme Toti.

How can a function value is displayed in a HTML tag with a return value from addEventListerner click?

Is it possible, if I can use "const Keys" as a react component i.e.: "class Keys extends React.Component".

 const Keys = ({ calcKeys, handleClick }) => (
    <div className="display-keys">
      {calcKeys.map(item => (
           <button onClick={() => handleClick(item.key)}>{item.key}</button>
       ))}
    </div>
)

Upvotes: 1

Views: 101

Answers (2)

kimchirichie
kimchirichie

Reputation: 15

yes. you certainly can re-write as class component. But the trend is to rewrite class components into functional.

What can be done as class component can also be achieved by the functional kind. Functional components also have the advantage of using hooks.

take a look at hooks

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371138

You can, all you need to do is reference the component's props in a render method:

class Keys extends React.Component {
  render() {
    const { calcKeys, handleClick } = this.props;
    return (
      <div className="display-keys">
        {calcKeys.map(item => (
             <button onClick={() => handleClick(item.key)}>{item.key}</button>
         ))}
      </div>
    );
  }
}

But it's somewhat odd to want to do - it makes the code longer without much reason, and React themselves recommend to try using functional components in new code when possible.

Upvotes: 5

Related Questions