A
A
Aidar Khayatov2019-09-11 12:36:40
JavaScript
Aidar Khayatov, 2019-09-11 12:36:40

What is the best way to import components in React?

The project gets a lot of shared components (buttons, switches, etc.). And in each component you have to import them separately.
There is an option to create a module in which to import all these components and return

export default { 
  Component1,
  Component2,
  Component3
}

Accordingly - to import only it. and from it already take the necessary components.
Is this the normal approach in the React world - and are there any downsides?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew Hecc, 2019-09-11
@Haiatov

We use this approach. I'll show you with an example action from redux, but it can also be used with components.
An index.js file is created in the directory with shared components. It exports all named exports from files in this folder like this: Index.js
file:

export * from './auth';
export * from './user';
export * from './interfaces';
export * from './search';
export * from './catalog';
export * from './classifier';

auth.js file:
export const getUserToken = ( login, password ) => (dispatch, getState) => {...}
export const registerUser = ( newUserData ) => ( dispatch, getState ) => {...}

Thus, then in any place where we need to get one of these files, we have one entry point through which we can get variables from several files at once:
import { getUserToken, doSmsng, doSmsngElse } from '../../../_actions';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question