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>
  );
})}
Answer from Tholle on Stack Overflow
Top answer
1 of 2
101

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}
2 of 2
6

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

Discussions

How to set variable in render with reactjs? - Stack Overflow
Note: If the output of ... the value outside render (avoid re-calculating when component re-renders). ... Sign up to request clarification or add additional context in comments. ... Although you can set local variables in the render, the use of props is recommended for better modifiability. So, you first 'declare' the property in the component: class ExampleComponent extends React.Component ... More on stackoverflow.com
🌐 stackoverflow.com
React - How do I assign a variable to the input value in another Component's class?
I am currently creating a damage calculator app with React. I am just starting out so bear with me. Here is my code for getting the input value of 'Atk'. This is currently in my component called ' More on stackoverflow.com
🌐 stackoverflow.com
reactjs - How to assign a value of a variable from a function in another function in React JS - Stack Overflow
It was an issue, the value of input ... val:e.target.value in change function. ... We'll Be In Touch - A New Podcast From Stack Overflow! ... We’re (finally!) going to the cloud! Call for testers for an early access release of a Stack Overflow extension... 2 how to pass variable from a function to render function in react... More on stackoverflow.com
🌐 stackoverflow.com
August 31, 2019
ReactJS - How to assign an JSX element to a variable and use it in render method
Hi Campers! Recently I’m working on this project of a music player and I have a Class Component “MuscicPlayer”, which has a render method like this: render() { let nowPlayingSong = this.state.songList.getSongAtIndex(this.state.nowPlayingSongIndex); let nowPlayingSongURL = nowPlayingS... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
September 28, 2018
🌐
Quora
quora.com › How-do-you-assign-value-to-a-variable-inside-a-map-function-in-ReactJS
How to assign value to a variable inside a map() function in ReactJS - Quora
Answer: You can’t. You need to add a block by using curly braces to your arrow function to have the space in between to assign a variable. ... Hopefully it helped people to understand that most of the things in React are about JavaScript (e.g. ...
🌐
W3Schools
w3schools.com › react › react_es6_variables.asp
React ES6 Variables
React Compiler React Quiz React Exercises React Syllabus React Study Plan React Server React Interview Prep React Bootcamp React Certificate ... Before ES6 there was only one way of defining your variables: with the var keyword. If you did not ...
🌐
Altcademy
altcademy.com › blog › how-to-use-variables-in-reactjs
How to use variables in ReactJS - Altcademy.com
November 8, 2023 - In this example, we use the curly braces {} to include the variables in the JSX code. JSX is a syntax extension for JavaScript that is used in ReactJS to describe what the UI should look like.
🌐
Stack Overflow
stackoverflow.com › questions › 52415450 › react-how-do-i-assign-a-variable-to-the-input-value-in-another-components-cla
React - How do I assign a variable to the input value in another Component's class?
class App extends React.Component { state = { stats: "", }; handleCange = e => this.setState( { stats: e.target.value } ); damageCalc = () => console.log( this.state.stats ); render() { return ( <div> <Atk onChange={this.handleCange} stats={this.state.stats} /> <CalculatorButton onClick={this.damageCalc} /> </div> ); } } const Atk = ( props ) => { const { stats, onChange } = props; return ( <div> <label>PHY/MAG ATK</label><br /> <input value={stats} onChange={onChange} type="number" /> <br /><br /> </div> ); }; const CalculatorButton = props => ( <button onClick={props.onClick}>Click</button> ); ReactDOM.render( <App />, document.getElementById( "root" ) ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
ReactJS - How to assign an JSX element to a variable and use it in render method
September 28, 2018 - Hi Campers! Recently I’m working on this project of a music player and I have a Class Component “MuscicPlayer”, which has a render method like this: render() { let nowPlayingSong = this.state.songList.getSongAtIndex(this.state.nowPlayingSongIndex); let nowPlayingSongURL = nowPlayingSong.songURL; let nowPlayingSongAlbumArt = nowPlayingSong.songAlbumArtLink; let nowPlayingSongTitle = nowPlayingSong.songTitle; let nowPlayingSongAuthor = nowPlayingSong.songAu...
🌐
Stack Overflow
stackoverflow.com › questions › 75394594 › why-i-cant-assign-value-to-variable-in-react-through-function-handler
Why I Can't assign value to variable in react through function handler
Directly changing the value of ... to update the value and rerender your content correctly. ... You can assign value as name = "asif" to name variable....
🌐
SheCodes
shecodes.io › athena › 39209-how-to-set-a-usestate-variable-in-react
[React] - How to set a useState variable in React - | SheCodes
Learn how to set a variable using the useState hook in React with this easy-to-follow guide and code example.
🌐
Altcademy
altcademy.com › blog › how-to-define-varaibles-in-reactjs
How to define varaibles in ReactJS - Altcademy.com
July 5, 2023 - Think of it like a box where you can put something (a value) and later retrieve it using the label (variable name) on the box. JavaScript is the language that ReactJS is based on. In JavaScript, you can declare a variable using three keywords: var, let, and const. Each has a different usage and scope. ... The difference between let and const is that once a const variable is assigned, it cannot be reassigned.
🌐
Thinkster
thinkster.io › tutorials › rendering-variables-in-react
Rendering Variables in React components - Thinkster
var Hello = React.createClass({ render: function() { var targetOfGreeting = "world"; return <div>Hello, { targetOfGreeting }!</div>; } }); Our component now displays “Hello, world!” — you can check out the working code here! The last thing worth mentioning is how you can use Javascript expressions to populate HTML attributes.
🌐
Medium
ajaynjain.medium.com › are-you-defining-variables-the-right-way-c56066d4692a
Are you defining variables the right way? | by Ajay n Jain | Medium
November 8, 2023 - Define Variables OUTSIDE Components if it should be Defined only ONCE. (like MAX_VALUE) use React refs when you want some value to be stored but NOT Render it on the screen.
🌐
Educative
educative.io › answers › how-to-pass-values-inside-attributes-in-react
How to pass values inside attributes in React
Lines 11 and 14: We can see how our variables are enclosed in curly braces to be passed. We may also need to update the data dynamically, such as upon a user's provided input. This can be done with the use of a useState hook. This hook is used for storing and passing dynamic data to components. Below are the steps we must follow to pass values using the useState hook: First, we will create a react component to pass the hooks data.
🌐
Reddit
reddit.com › r/reactjs › why would you declare variables below a component?
r/reactjs on Reddit: Why would you declare variables below a component?
January 30, 2024 -

I recently delved into the latest React documentation and observed a recurring pattern of declaring variables below the component:

const Component = () => {  
  return <div>{dogName}</div>;  
};  
const dogName = 'Spot';  

At work, we declare them above the component:

const dogName = 'Spot';

const Component = () => {  
  return <div>{dogName}</div>;  
};  

On one hand, I like that it keeps the bloat on the bottom so that the component's logic is immediately visible. However, in larger components, it means that I wouldn't know the value of dogName until I scroll to the bottom. Logically, even though variables are hoisted to the top, I prefer seeing a variable declared before its usage.

Is there a specific reason behind the pattern of declaring variables below the component? I'd love to gather insights and opinions.

(Here's an example from the React documentation showcasing this pattern. I've noticed this pattern in a few other places as well.)

🌐
React
react.dev › learn › state-a-components-memory
State: A Component's Memory – React
In React, this kind of component-specific memory is called state. How to add a state variable with the useState Hook ... Here’s a component that renders a sculpture image. Clicking the “Next” button should show the next sculpture by changing ...
🌐
Educative
educative.io › home › courses › javascript fundamentals before learning react › variable declarations in javascript
Variable Declarations in JavaScript
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') ); Also, JavaScript didn’t have a dedicated keyword to declare constants only which is why const was introduced. The variables assigned using const are read-only which means that once they are initialized using const, they cannot be reassigned.
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
How to Use Variables within Classes | Pluralsight
March 19, 2020 - In the above example, there is one static variable called num1 whose value is fixed. This means no one can change its value into the current component, but they can use it for the rendering purpose. In the same way, the state object can also be used as a static value. import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { state = { name: 'Hello World', age: '30' }; render() { const { name, age } = this.state; console.log(this.state) return ( <div> </div> ); } } render(<App />, document.getElementById("root"));
🌐
Stack Overflow
stackoverflow.com › questions › 72947495 › how-can-i-assign-value-to-a-variable-inside-a-ui-component-in-react
How can I assign value to a variable inside a UI component in React?
July 12, 2022 - But I am unable to set the state ... pass the names of 2 companies to . ... you use default value of useState is array and you assign value as string in `setCompany1(companyData.name)....