reusing same imported component file in javascript

To reuse the same imported component file in JavaScript, we need to import it as a module and then use it in different files wherever we want.

Here's an example of importing a component file named Button.js and using it in two different files:

Button.js

index.tsx
import React from 'react';

const Button = ({onClick, children}) => {
    return (
        <button onClick={onClick}>
            {children}
        </button>
    )
}

export default Button;
191 chars
12 lines

File1.js

index.tsx
import React from 'react';
import Button from './Button';

const File1 = () => {
    return (
        <div>
            <h1>This is File1 Component</h1>
            <Button onClick={() => console.log('Button clicked in File1')}>Click me in File1</Button>
        </div>
    )
}

export default File1;
301 chars
14 lines

File2.js

index.tsx
import React from 'react';
import Button from './Button';

const File2 = () => {
    return (
        <div>
            <h1>This is File2 Component</h1>
            <Button onClick={() => console.log('Button clicked in File2')}>Click me in File2</Button>
        </div>
    )
}

export default File2;
301 chars
14 lines

In the above example, we have created a Button component in Button.js and exported it as a module using export default.

Then, in File1.js and File2.js, we have imported the same Button component using import Button from './Button'. This way, we can reuse the same Button component in multiple files while maintaining its reusability.

gistlibby LogSnag