Skip to content
Advertisement

Split up functionalities across project in React?

Alright so I’m new to React, and have made an application which gets some data from an API and stores it into a table. It worked, but most of the code was in a single file which irritated me a lot. Now I’m trying to split it across multiple files, but without much luck as of yet.

I followed an answer which said I could just create a APIManager and use the following code:

import React from 'react';

const base_url = 'https://europe-west1-single-router-309308.cloudfunctions.net/GET?';

export let buildURL = (offset, pagination, product_name, store_name) => {
    [...]
}

However this gives me a TypeError: Object(...) is not a function. I tried it with a plain function, export function, and this, but nothing works. Should I make a component out of it? This is where the code gets called:

<div className='header'>
          <Form handleSubmit={(offset, pagination, product_name, store_name) => {buildURL(offset, pagination, product_name, store_name)}}/>
</div>

Advertisement

Answer

Alright, with the help of @digitalbreed I managed to fix it! I changed

import buildURL from './src/managers/APIManager';

to

import * as APIManager from './src/managers/APIManager';

and changed my reference to the code from

<Form handleSubmit={(offset, pagination, product_name, store_name) => { APIManager.buildURL(offset, pagination, product_name, store_name)}}/>

to

<Form handleSubmit={() => this.handleSubmit(offset, pagination, product_name, store_name)}/>

with

handleSubmit(offset, pagination, product_name, store_name){
  var url = APIManager.buildURL(offset, pagination, product_name, store_name);

And it works fine now. Thanks for the help, digitalbreed!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement