Search code examples
reactjsreact-functional-componentreact-class-based-component

How can I convert class component to functional component?


I have a class based component, and I want to convert to the functional based component, my code is below:

import { enableRipple } from '@syncfusion/ej2-base';
import { DropDownButtonComponent } from '@syncfusion/ej2-react-splitbuttons';
import * as React from 'react';
import * as ReactDom from 'react-dom';
enableRipple(true);
// To render DropDownButton.
class App extends React.Component {
    constructor() {
        super(...arguments);
        this.items = [
            {
                text: 'Display Settings'
            },
            {
                text: 'System Settings'
            },
            {
                text: 'Additional Settings'
            }
        ];
    }
    render() {
        return (<div>
        <DropDownButtonComponent items={this.items} iconCss='e-icons e-image' cssClass='e-caret-hide'/>
      </div>);
    }
}
ReactDom.render(<App />, document.getElementById('button'));

But I did not get it how to convert this part below, any idea?

  constructor() {
        super(...arguments);
        this.items = [
            {
                text: 'Display Settings'
            },
            {
                text: 'System Settings'
            },
            {
                text: 'Additional Settings'
            }
        ];
    }

Solution

  • This could be converted to functional component as bellow:

    import { enableRipple } from '@syncfusion/ej2-base';
    import { DropDownButtonComponent } from '@syncfusion/ej2-react-splitbuttons';
    import * as React from 'react';
    import * as ReactDom from 'react-dom';
    
    enableRipple(true);
    
    const App = () => {
      const items = [
        {
          text: 'Display Settings',
        },
        {
          text: 'System Settings',
        },
        {
          text: 'Additional Settings',
        },
      ];
    
      return (
        <div>
          <DropDownButtonComponent
            items={items}
            iconCss="e-icons e-image"
            cssClass="e-caret-hide"
          />
        </div>
      );
    };
    
    ReactDom.render(<App />, document.getElementById('button'));