0

I am trying to create a UI library for (P)React. Repo can be viewed here.

A setup function is called to initiate createElement/forwardRef functions. These are set to let variables so they can be accessed inside other files. This question is related to this and this. Variables are live views, but why are variables with functions not live views?

// setup.ts
let forwardRef
let createElement

function setup(createElementIn, { forwardRef : fw }) {
  forwardRef = fw
  createElement = createElementIn
}

In another function it is imported like this

// box.ts
import { forwardRef, createElement } from './setup'

// this works
function Box(props, ref){
  console.log('forwardRef', forwardRef) // correct function

  return createElement('div', { ...props, ...(ref && ref) })
}

// this does not work because forwardRef is undefined
export forwardRef ? forwardRef(Box) : Box

Box is called like this

import { useRef, createElement, forwardRef } from 'react'
import { Box, setup } from 'juhuui'

// this is called only once
setup(createElement, { forwardRef })

function Hello () {
  const myRef = useRef(null);

  return (<Box ref={myRef}>Hello</Box>)
}

Can you please tell me how my code can be restructured to work?

Espen Finnesand
  • 475
  • 7
  • 22
  • Can you provide an actual minimum reproducible example in the question? You use `forwardRef` as a function but there's no indication if it is actually a function and if it remains one throughout the code (since it is a mutable export). – apokryfos Jul 13 '20 at 11:00
  • Thank you for the fast reply. I added a minimal setup in the last code example. The missing part was showing how the setup function works. – Espen Finnesand Jul 13 '20 at 11:10
  • Well you've got yourself in a bit of a bind here. You import `box.ts` and `setup.ts` at the same time meaning `forwardRef` will be undefined when you hit the export part. If you could (somehow) import `setup.ts` first. Do `setup(...)` and then import `box.ts` you might have more success, but this does look very messy. Perhaps you could instead have `setup.ts` run the setup code on import and only import that file, if that is an option – apokryfos Jul 13 '20 at 12:36
  • Yes it feels quite messy. Even if **setup.ts** and **box.ts** are imported in different files, the result is sadly the same. I have also tried a setup function that returns `{ box: forwardRef && box }` and `export const box = setup.box` with the same result. – Espen Finnesand Jul 13 '20 at 13:40

0 Answers0