Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a value to a variable in JSX for ReactJS

Tags:

reactjs

jsx

{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 }
like image 435
Asim K T Avatar asked Oct 05 '17 09:10

Asim K T


People also ask

Can JSX be assign to a variable?

Therefore, JSX is designed as a statically-typed language. All the values and variables have a static type and you can only assign a correctly-typed value to a variable.

How do I declare an element in JSX?

Embedding Expressions in JSX In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces: const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>; You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2 , user.


2 Answers

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>
  );
})}
like image 119
Tholle Avatar answered Oct 01 '22 21:10

Tholle


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>
)}
like image 36
dominik791 Avatar answered Oct 01 '22 21:10

dominik791