0

I have a product component that renders n number of sections. The code in the product component:

let sections = this.state.product.sections.map((section, idx) => {
  return (
    <Section sectionType={section.id} section={section} />
  )
})

return (
  <div>
    {this.state.product.name}
    {sections}
  </div>
)

The code in the section component:

renderSection() {
 switch (this.props.sectionType) {
  case 'heroImage':
    return (
      <img src={image.url} />
    )
  case 'doublePane':
    this.props.section.items.map((item, idx) => {
      console.log(item.id);
      if (1 === 1) {
        return (
          <div>hi</div>
        )
      }
    })
  default:
    return (
      <div>hey there</div>
    )
}
}

render() {
  return (
    <div>
      {this.renderSection()}
    </div>
)
}

I added the 1===1 line just to make sure it would execute, but the output of my code is still

  1. the heroImage case properly executes
  2. the console log of item.id happens (so we definitely enter the doublePane block), but the code inside of the 1===1 block does not execute.

Any idea what's happening here to not allow me to run the code inside of the 1===1? Thanks in advance!

2
  • 2
    Your return is inside the .map() callback... nothing is being returned in the actual switch case Commented Mar 17, 2018 at 17:52
  • If the console.log(item.id) is executing then return ( <div>hi</div> ) also executed. The problem is you are returning inside .map(). Commented Mar 17, 2018 at 17:52

1 Answer 1

2

You need to return the result of the mapping function, in addition to returning within the mapping function:

renderSection() {
  switch (this.props.sectionType) {
    case 'heroImage':
      return (
        <img src={image.url} />
      );
    case 'setOfTwo':
      return (
        <div>
          {this.props.section.items.map((item, idx) => {
             console.log(item.id);
             return (
               <div>hi</div>
             );
          })}
        </div>
      );
    default:
      return (
        <div>hey there</div>
      )
  }
}

Wrapping the return value in a div isn't necessarily required, but I prefer to return a consistent item (in this case a single JSX element) from functions.

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

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.