A
A
Alexey2021-09-07 17:31:00
React
Alexey, 2021-09-07 17:31:00

The tag fires faster than the condition in the react component, how to fix it?

React component:

export default function Downloading(props) {
  return (
    <>
      {
        props.isDownload
        ? <>{props.children}</>
        : <div>Загрузка...</div>
      }
    </>
  )
}

As I understand it, with static props.children it works fine, but with the following line of the problem:
<Downloading isDownload={isDownload}>
  <img src={`http://openweathermap.org/img/wn/${data.current.weather[0].icon}@4x.png`} alt="Weather" />
</Downloading>


The data.current.weather[0].icon object is loaded asynchronously and at the start of rendering - this object does not exist - the "Cannot read properties" error immediately flies. As I understand it, the string in the tilde is first processed, and only then the condition check in the Downloading component begins.

Is it possible to somehow make it so that the condition in the Downloading component is first processed, and only then proceeds to processing the img tag?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2021-09-07
@Evelate

Something like that

export default function Downloading(props) {
  return (
    <>
      {
        props.isDownload
        ? <>{props.children()}</>
        : <div>Загрузка...</div>
      }
    </>
  )
}



<Downloading isDownload={isDownload}>
  {() => <img src={`http://openweathermap.org/img/wn/${data.current.weather[0].icon}@4x.png`} alt="Weather" />}
</Downloading>

https://reactjs.org/docs/render-props.html#using-p...
should work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question