Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Component wait for required props to render

I am declaring a component inside of a parent component. I want to establish specific props in one file, and then in the parent component, I want to be able to establish the other props for the child components all at once (since they are shared properties.. for the most part).

My problem is that the child component attempts to render and fails since the required prop types aren't being established at first.

Is there a way to tell the child component to wait for the required props to render?

In the ParentComponent render function, I call another function to run React.Children.map() and append props to ChildComponent.

The (rough) section where the child component is being rendered:

<ParentComponent>
    <ChildComponent
        attribute="test_attribute"
        label="Child Component"
        type="number"
        width={3}
    />
</ParentComponent>
like image 787
cmwall Avatar asked May 18 '16 19:05

cmwall


People also ask

How do you wait for a component to render in React?

To wait for a ReactJS component to finish updating, we use a loading state in our react application by use of the conditional rendering of the component. This can be achieved by the use of the useState and useEffect hooks in the functional components.

How do you wait for Promise to resolve in React?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

How is componentDidUpdate used in functional components?

Every time the “Resize” button is clicked and the setState function is called, the componentDidUpdate function starts running, and the component gets updated. Also, you can use componentDidUpdate to get the ref to the div DOM element and adjust the basic dimensional properties like width and height.

How do you wait for state update in React?

Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.


1 Answers

You can use a conditional render statement to only render the child when the props are populated:

let {foo, bar} = this.props;

<ParentComponent>
    { foo && bar ? <ChildComponent foo={foo} bar={bar} /> : null }
</ParentComponent>

Or instead of null you could render a <LoadingSpinner /> or something.

like image 96
Aaron Beall Avatar answered Sep 29 '22 14:09

Aaron Beall