0

I only want to render array values as elements, if the array has values and exists. In my case there is an array of colors, the user can set the current color_theme, which is represented by its index. On start there should no color_theme be chosen. My render function will try to render the current color_color_theme, but there is noch current_color_index. How can I check if there is an exsiting colorsheme before the rendering? I cannot write a return before the redering, because there are other elements, that have to be rendered.

 data = {
   "colorthemes" : [ ["blue","red"], ["black","grey"] ],
   "current_color_index": "", 

   ....//more 
 }


    render: function() {

    return (
        <div>
            <ul>
                //other stuff is rendering
            </ul>
            <ul>
                    {this.state.data.colorthemes[this.state.data.current_color_index].map(function(item, i) {
                      ....
                    }, this)}  
            </ul>
       </div>

2 Answers 2

2

Just use an if condition, inside the jsx, something like

{
    condition ?
    <MyRenderElement /> :
    null
}

If the condition is not met, nothing will be rendered by this block of code.

SUGGESTION: I would suggest you to have reasonable default values rather than using such an if condition. Helps you to keep lesser control flow paths and lesser bugs.

Sign up to request clarification or add additional context in comments.

2 Comments

the loop breaks, where in the loop can I place a condition? -> .map(function(item, i)...
You are using the functional programming constructs wrongly. First map everything and then use filter to remove all unwanted things.
1

I think you could do it in a simpler manner like:

{ condition && <MyRenderElement/> }

I would say that this makes a bit more sense for your case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.