0

Using styled-components, if you have Title defined in an imported file:

//comp.js

const Title = styled.h1`
   color: red;
`;

Is it possible to use Title without having to define Title in the index.js? For example,

//index.js

import "./components.js";

render(
   <Title>Text here</Title>,
   document.getElementById("root")
);

I'm not sure if this is possible, and haven't found a way to do it and I may be out of my depth in thinking of a solution. In this example, Title would be re-used many times so, if I have pre-defined set of multiple components, I kind of want to avoid having to define every component (Title, Button, Field, etc) in index.js since it's already being defined somewhere else.

Hope this makes sense.

Thanks!

Dav
  • 5
  • 2

2 Answers2

1

Components are meant to be reused. You basically can export a component, let it be default export or named export and then import it accordingly in another file and then use it there.

Example,

File 1

export default someComponent;

File 2

import SomeComponent from 'path to file 1';

or

File 1

export someComponent;

File 2

import {someComponent} from 'path to file 1'

You can read more about export/import here.

I think you can also try something like this way,

import * as SomeName from 'path';

Then, SomeName.Component

gprathour
  • 13,193
  • 5
  • 56
  • 85
  • So, I would need to write `import { Title, compTwo, compThree } from 'path to file 1'` ? There's no way to just import `file 1` and then be able to use `` or any other components within that file? – Dav Dec 04 '19 at 08:18
0
class Header extends PureComponent {

    render() {
        return (
            <div>
              Stuff
            </div>
        );
    }
}

export default Header;

Then

import Header from '../component';
<Header></Header>
Jon Jones
  • 861
  • 1
  • 8
  • 17