Home > database >  How to create button react component?
How to create button react component?

Time:11-07

I created simple React app and need to add Button Component. Unfortunately my code is not working. How I can fix it? Button realisation (React):

import React from 'react';

const Button = (props) => {
    return <button className="button">
        {props.children}
    </button>;
}

export { Button };

Test code:

import React from 'react';
import { shallow } from 'enzyme';

import Button from './Button';

describe('Button', () => {
    /**

     * children - button text

     */

    it('Button with text', () => {
        const component = shallow(<Button>Button</Button>);

        expect(component.html()).toEqual('<button >Button</button>');
    });
});

files in dir

Error in test:

 Expected: "<button class=\"button\">Button</button>"
 Received: null

CodePudding user response:

can you please try this,

it('Button with text', () => {
        const component = shallow(<Button>Button</Button>);

        expect(component.html()).toEqual('<button class=\"button\">Button</button>');
    });

CodePudding user response:

This import line:

import Button from './Button';

is asking the build to get the default export from the module, but you're exporting that component inside an object.

So either:

export default Button;

Or:

import { Button } from './Button';

(I'd also suggest adding parentheses around your JSX in your return, and using importing some CSS specific to that component.)

function Button(props) {
  return (
    <button className="button">
      {props.children}
    </button>;
  );
}

export default Button;
  • Related