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 OverflowEverything 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 use an IIFE(Immediately Invoked Function Expression)
{props.stories.map((story) =>
<div key={story.id}>
{(() => {
story = story.story
return <SliderItem story={story} />
})()}
</div>
)}
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" });
}
}
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.
How to set variable in render with reactjs? - Stack Overflow
React - How do I assign a variable to the input value in another Component's class?
reactjs - How to assign a value of a variable from a function in another function in React JS - Stack Overflow
ReactJS - How to assign an JSX element to a variable and use it in render method
Videos
render() {
// assuming 'changeMyVariable' returns a value
const myVariable = this.changeMyVariable();
return (
<div>{myVariable}</div>
);
}
Actually you can invoke the function inside your JSX itself:
<div>{this.changeMyVariable()}</div>.
Note: If the output of this.changeMyVariable() never changes based on new props, it is better to compute the value outside render (avoid re-calculating when component re-renders).
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 {
static propTypes = {
myVariable: React.PropTypes.string.isRequired,
};
static defaultProps = {
myVariable: 'Default Value'
};
And then, you render this prop at the ExampleComponent render method:
render() {
return (
<div>{this.props.myVariable}</div>
);
}
To use this prop when you render ExampleComponent:
render() {
<ExampleComponent myVariable='example'/>
}
How about using state!!
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
class App extends React.Component {
constructor (props) {
super(props);
this.state ={valueOfInput:''}
}
change(e){
valueOfInput = e.target.value;
this.setState({valueOfInput});
}
submit(ev){
ev.preventDefault();
alert(this.state.valueOfInput)
}
render() {
return(
<div>
<form action="">
<input onChange={this.change.bind(this)} type="text" value={this.state.valueOfInput}/>
<input onClick={this.submit.bind(this)} type="submit" value='submit'/>
</form>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Happy coding!!! Hope this helps.
Storing value of input in valueOfInput variable can be done by declaring it into class level using this.
constructor(props) {
super(props);
this.state = { val: "test" };
this.valueOfInput = null;
}
change(e) {
this.valueOfInput = e.target.value;
}
submit(ev) {
ev.preventDefault();
alert(this.valueOfInput);
}
But it won't work as expected as we're not updating value of input with new value. So to solve this we have to store new input value into state and use that value in input.
change(e) {
this.valueOfInput = e.target.value;
this.setState({
val: e.target.value
});
}
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.)