Asim K T
Asim K T

Reputation: 18134

Assign a value to a variable in JSX for ReactJS

{props.stories.map((story) =>
    <div key={story.id}>
        {story = story.story}
        <SliderItem story={story} />
    </div>
)}

The above code throws an error saying:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys

because story in line number 3 is an object.

I can move that condition directly as <SliderItem story={story.story} />, but I want to know if there is any way I can assign my calculated value to a variable and use it in JSX?

I want to apply some logic like:

{ let storyObj = story.type === 'story' && story.story ? story.story : story }

Upvotes: 32

Views: 72525

Answers (6)

KMA Badshah
KMA Badshah

Reputation: 1115

You can use an IIFE(Immediately Invoked Function Expression)

{props.stories.map((story) =>
    <div key={story.id}>
        {(() =>  {
          story = story.story
          return <SliderItem story={story} />
        })()}
    </div>
)}

Upvotes: 11

Devin Rhode
Devin Rhode

Reputation: 25267

I think this would be a fairly elegant solution:

function someReactFunctionalComponent(props) {
  const vars = {}

  return (
    <div>
      <h1>... lots of code ...</h1>
      {vars.someFoo_s = bar ? dance : undefined}
      <ul>
        {
          vars.someFoo=normalizeFoo(vars.someFoo_s),
          vars.someFoo_s.map((aFoo) => (
            <li>{aFoo}</li>
          ))
        }
      </ul>
    </div>
  )
}

Upvotes: 7

Chase DeAnda
Chase DeAnda

Reputation: 16441

Why don't you just pass in story.story??

  {props.stories.map((story) =>
    <div key={story.id}>
      <SliderItem story={story.story} fallback={story} />
    </div>
  )}

In your component if this.props.story is undefined then use this.props.fallback.

Upvotes: 0

dominik791
dominik791

Reputation: 752

You can create a function outside the render() that will get correct value:

function getStory(storyObj) {
  return storyObj.type === 'story' && storyObj.story ? storyObj.story : storyObj;
}

And then use it in JSX:

{props.stories.map(storyObj =>
  <div key={storyObj.id}>
     <SliderItem story={getStory(storyObj)} />
  </div>
)}

Upvotes: 12

Develer
Develer

Reputation: 41

Though I wouldn't recommend it as it really obfuscates your code, you can use the comma operator to allow you to assign a value:

{story = story.story, <SliderItem story={story} />}

I'm not sure why you would want to do this however?

Upvotes: 3

Tholle
Tholle

Reputation: 112777

Everything between {} in the JSX is just JavaScript, so you can do the following:

{props.stories.map((story) => {
  const storyObj = (story.type === 'story' && story.story) ? story.story : story;
  return (
    <div key={story.id}>
      <SliderItem story={storyObj} />
    </div>
  );
})}

Upvotes: 32

Related Questions