{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 }
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.
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.
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>
);
})}
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>
)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With