0

I'm new to the ReactJS framework and I have these lines of code:

//rest of code omitted...

const dateToTime = date => date.toLocaleString('en-GB');
const dateString = `${order.data.created_at}Z`;
const localDate = new Date(dateString);

The other part of the code is inserted in that part of the component. The code is working perfectly.

//rest of code omitted...

return (
     <React.Fragment key={index}>
        <td>{dateToTime(localDate) || emptyMessage}</td> //<-----code continuation  

//rest of code omitted...

I would like to do a utility function to import into various components, How do I do this?

I want to reuse the code

claudiopb
  • 1,056
  • 1
  • 13
  • 25

2 Answers2

0

Just like you export any other thing in JS.

// util.js
export function myFunc(params){
    // Do stuff
}


// yourComponent.js
import {myFunc} from 'path/to/util.js';

//rest of your code
// you can use myFunc(params) anywhere you need
Ron B.
  • 1,502
  • 2
  • 7
0

You make utils.js somewhere in your app. Then import it to your file that you want.

import utils from '../../utils/utils.js';

Use destructuring ES6

const { dateToTime, dateToString, localDate } = utils;

Then you can use it in your file

console.log(dateToTime);
nabil arta
  • 164
  • 1
  • 3
  • Thank you. I will test it now and I ´m going to return soon. – claudiopb May 19 '21 at 08:51
  • Can you explain it to me in more detail please? how would the utils body look? – claudiopb May 19 '21 at 08:52
  • same line code but in the end you use: const dataToExport = { dateToTime, dateToString, localDate }; export default dataToExport; – nabil arta May 19 '21 at 08:56
  • I don't know which of these variables I return in the function : const dateToTime = date => date.toLocaleString('en-GB'); const dateString = `${order.data.created_at}Z`; const localDate = new Date(dateString); – claudiopb May 19 '21 at 08:58
  • Ah you need to import the data neccesary for that 3 lines of code. If your 'order' data is only available in current js file, you need to make and import a function like the answer below, and pass the data to the variable, just like a normal function – nabil arta May 19 '21 at 09:04
  • I didi this way andit didn't work. There appears an error message: Parsing error: 'import' and 'export' may only appear at the top level `code` export function myFunc(inputDate) { const dateToTime = date => date.toLocaleString('en-GB'); const dateString = `${inputDate}Z`; const localDate = new Date(dateString); const dataToExport = { dateToTime, dateToString, localDate }; export default dataToExport } `code` – claudiopb May 19 '21 at 09:14
  • https://stackoverflow.com/questions/37902849/import-and-export-may-only-appear-at-the-top-level – nabil arta May 19 '21 at 09:30