react component return problem when props are null

Viewed 32
export default function RenderPages({storage, setStorage, state, setState}){
  let elRefs= useRef()
  
  if(!storage) return
  if(!state.currentFileId || !state.currentFolderId) return
  
  const content = storage[state.currentFolderId][state.currentFileId].content

  return (
    <div className="writing">
      <input ref={elRefs}/>
      {content.map((page, index)=>
      <div className='textarea'>
        <textarea placeholder='write here' value={page} id={"page"+index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
      </div>)}
    </div>
  )
}

There are some props(state, storage) and they are sometimes null value. What I am doing now is checking the values of state and storage, returning blank early if those values are null. If I don't return in advance, the variable "content" get error because it needs state and storage value. Now this is the problem. I want to use "useRef", and if the component return early "elRefs" is assigned null value, so I can't get DOM element. What should I do?

1 Answers

I put your booleans into single function and seperated the renderable part of component. If bool is false, that component is simply not rendered. Of course you can put in there other component which shows error data or loading gif or something like that. Hope this works!

export default function RenderPages({ storage, setStorage, state, setState }) {
  const elRefs = useRef()
  const content = storage[state.currentFolderId][state.currentFileId].content

  // content to render in seperate component
  const Pages = () => (
    <div className="writing">
      <input ref={elRefs} />
      {
        content.map((page, index) =>
          <div className='textarea'>
            <textarea
              placeholder='write here'
              value={page} id={"page" + index}
              onChange={(e) => onChange(e, index)}
              rows={rows}
              cols={cols}
            />
          </div>
        )
      }
    </div>
  )

  // decide to or not to render component
  const renderable = storage &&
    state.currentFileId &&
    state.currentFolderId

  return (
    <>
      {
        renderable
          ? <Pages />
          : <></> // returns empty component 
      }
    </>
  )
}

Related