Search code examples
javascripthtmlreactjsconditional-rendering

How to render a component, that contains an opened and not closed tag? React.js


I have an objective to make a component, that renders cards with nested ul tags like this: needed from data like this, that's being passed down with props from a parental component: data

For that I set markers at the end of the lines where the nested ul should start, e.g. ":" when the nested ul should open and "." when the nested ul should close. But to make this code work, I need to render opened, but not closed tags.

let inUl = false;
<div className="cardBody">
        {props.body.map((el, index) => {
          if(el.endsWith(":")){
            inUl = true;
            return <li>{el}<ul>
          } else if(inUl && el.endsWith('.')){
            inUl = false;
            return <li>{el}</li></ul>
          } else {
            return <li>{el}</li>
          }
        })}
  </div>

Any help will be greately appreciated, I've a close deadline, and right now I'm literally stuck on the last part of the project - this.


Solution

  • But to make this code work, I need to render opened, but not closed tags.

    This is a fundamental misunderstanding of how React works. You use tags in the source code to define elements, which are objects. You can't have an opening tag without a closing tag any more than you can have an opening { for an object initializer without a closing }.

    Instead, you have a component that you pass children to, and it renders the children within its component. E.g.:

    const UnorderedList = props => <ul>{props.children}</ul>;
    

    ...which is used like this (i.e., in a render somewhere):

    return <UnorderedList><li>...</li><li>...</li></UnorderedList>;