Skip to content
Advertisement

Conditional rendering in React based on current component state

I am struggling with figuring out how to implement conditional rendering in React. Basically, what I want to do is this: if there is a reviewResponse in the reviewResponses array, I no longer want to render the reviewResponseForm. I only want to render that ReviewResponse. In other words, each review can only have one response in this app. I am not sure what I am doing wrong when trying to implement this logic. I know I need to implement some kind of conditional statement saying if the length of my reviewResponses array is greater than 0, I need to render the form. Otherwise, I need to render that reviwResponse. Every statement I have written has not worked here. Does anybody have a suggestion? Here is my code so far:

My review cardDetails component renders my ReviewResponseBox component and passed the specific reviewId as props:

JavaScript

Then eventually I want this component, ReviewResponseBox, to determine whether to render the responseform or the reviewresponse itself, if it exists already.

JavaScript

Here are the ReviewResponseForm and ReviewResponse components:

JavaScript
JavaScript

Any advice would be helpful, thank you.

Advertisement

Answer

If I understand your question correctly, you want to render ReviewResponseForm if the this.state.reviewResponses state array is empty.

Use the truthy (non-zero)/falsey (zero) array length property to conditionally render either UI element.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement