This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Why doesn't my arrow function return a value?
(1 answer)
Closed 1 year ago.
I know this is kind of a basic question... but I am just learning React and am not so familiar with Javascript as well.
App.js
return (
<div >
<h1>My Weather dashboard</h1>
<div className="container">
{weatherCards.map((obj, index) => {
<Card {...obj}/>
})}
</div>
</div>
)
Card.js
const Card = ( props ) => {
return (
<div className="card">
<img src={props.iconLink}/>
<div className="caption">{props.iconName}</div>
<h3>Day: {props.day}</h3>
<h3>time: {props.time}</h3>
<h3>temperature: {props.temperature}</h3>
</div>
)
}
export default Card
The map does not seem to be displaying anything.
Looks like you forgot the return in the map method
<div className="container">
{weatherCards.map((obj, index) => {
return <Card {...obj}/>
})}
</div>
You can directly return the component like below
return (
<div >
<h1>My Weather dashboard</h1>
<div className="container">
{weatherCards.map((obj, index) => <Card {...obj}/>)}
</div>
</div>
)
So in arrow function if you give anything after => that will be returned on every iteration. So if you give {}-Which is a function body it will return the function body. But if you give any variable or Componenet it will directly return that. We do this if we need to return any plain object.But sometime you have to do some logical execution, that time you can define a function body. But as you are defining a function body you must use the return key like this below
return (
<div >
<h1>My Weather dashboard</h1>
<div className="container">
{weatherCards.map((obj, index) => {
// your code here
return <Card {...obj}/>
})}
</div>
</div>
)
Related
I have my component CountDownSquare I want to disappear once the timer is done fully counting down. I have Data in homePageData that holds the main text in a h3 element, this text should appear once the timer is fully done. Here's a ternary statement I attempt to assign but it isn't assigned to anything the way I thought it would be. Here is a snippet of what I thought of
const { homePageData } = props;
{homePageData[0].showCountdown ? <CountDownSquare/>: styles.homeBody}
return (
homePageData && (
<Layout>
<div className={styles.Home}>
<Image src={wordmark} alt="Hammer and Hope wordmark" />
<CountDownSquare >
</CountDownSquare>
{/* <div className={styles.homeBody}>
<h3 className={styles.mainText}>{homePageData[0].mainText}</h3> */}
<Nav />
</div>
</Layout>
)
);
} ```
I am assuming homePageData[0].showCountDown is a boolean which is true if the countdown is complete in the parent component.
You need to add conditions while rendering your component.
The following snippet will render the CountDownSquare component and the h3 tag with homePageData[0].mainText if homePageData[0].showCountdown is true.
const { homePageData } = props;
return (
homePageData ?? (
<Layout>
<div className={styles.Home}>
<Image src={wordmark} alt="Hammer and Hope wordmark" />
{homePageData[0].showCountdown ??
<CountDownSquare >
</CountDownSquare>
<div className={styles.homeBody}>
<h3 className={styles.mainText}>{homePageData[0].mainText}</h3>
</div>
}
</div>
</Layout>
)
);
I have data stored in an object and I want to loop through the data and set it as the props for my component.
My component is a card, and I want to show a card for every piece of data in the loop.
This is code so far -
function App() {
let title = [];
for (let key in projectDataObject) {
let newObj = projectDataObject[key].sites;
for (let key in newObj) {
title = newObj[key].title;
}
return (
<div className="App">
<header className="App-header">
<Card title={title}></Card>
</header>
</div>
);
}
}
export default App;
The problem here is because of the "return" it stops the loop at the first item, and does not loop through everything else.
How can I do this?
use it like this:
<div className="App">
<header className="App-header">
{Object.keys(yourObject).map(function(key) {
return <Card title={yourObject[key].title} />;
})}
</header>
</div>
This code doesn't make any sense. You're just taking the last one as the title, so looping is pointless.
for (let key in newObj) {
title = newObj[key].title;
}
Since I can't really tell what you're trying to do there, I'll make an assumption to get you pretty close. It looks like you're trying to pull out all of the titles from your object graph, so let's do that first.
function App() {
const titles = /* I can't tell what your data structure is,
so flatten it to get all of the titles out and into an array here */
return (
<div className="App">
<header className="App-header">
{/* this will put a list of cards in the header */}
{titles.map(title => <Card title={title}/>)}
</header>
</div>
);
}
}
export default App;
I have seen similar questions here, but these haven't been helpful so far.
I have a component that has an array state:
eventData: []
Some logic watches for events and pushes the objects to the state array:
eventData.unshift(result.args);
this.setState({ eventData });;
unshift() here is used to push the new elements to the top of the array.
What I want to achieve is rendering the content of the state array. I have written a conditional that checks for a certain state, and based on that state decides what to output.
let allRecords;
if (this.state.allRecords) {
for (let i = 0; i < this.state.eventData.length; i++) {
(i => {
allRecords = (
<div className="event-result-table-container">
<div className="result-cell">
{this.state.eventData[i].paramOne}
</div>
<div className="result-cell">
{() => {
if (this.state.eventData[i].paramTwo) {
<span>Win</span>;
} else {
<span>Loose</span>;
}
}}
</div>
<div className="result-cell">
{this.state.eventData[i].paramThree.c[0]}
</div>
<div className="result-cell">
{this.state.eventData[i].paramFour.c[0]}
</div>
<div className="result-cell">
{this.state.eventData[i].paramFive.c[0] / 10000}
</div>
<div className="result-cell-last">
{this.state.eventData[i].paramSix.c[0]}
</div>
</div>
);
}).call(this, i);
}
} else if (!this.state.allRecords) {
for (let i = 0; i < this.state.eventData.length; i++) {
if (this.state.account === this.state.eventData[i].paramOne) {
(i => {
allRecords = (
<div className="event-result-table-container">
<div className="result-cell">
{this.state.eventData[i].paramOne}
</div>
<div className="result-cell">
{() => {
if (this.state.eventData[i].paramTwo) {
<span>Win</span>;
} else {
<span>Loose</span>;
}
}}
</div>
<div className="result-cell">
{this.state.eventData[i].paramThree.c[0]}
</div>
<div className="result-cell">
{this.state.eventData[i].paramFour.c[0]}
</div>
<div className="result-cell">
{this.state.eventData[i].paramFive.c[0] / 10000}
</div>
<div className="result-cell-last">
{this.state.eventData[i].paramSix.c[0]}
</div>
</div>
);
}).call(this, i);
}
}
}
Problems that I have with this piece of code:
The code always renders the very last value of eventData state object.
I would like to limit the rendered elements to always show not more than 20 objects (the last 20 records of the state array).
paramTwo is a bool, and according to its value I expect to see either Win or Loose, but the field is empty (I get the bool value via the console.log, so I know the value is there)
Is this even the most effective way of achieving the needed? I was also thinking of mapping through the elements, but decided to stick with a for loop instead.
I would appreciate your help with this.
A few things :
First, as the comments above already pointed out, changing state without using setState goes against the way React works, the simplest solution to fix this would be to do the following :
this.setState(prevState => ({
eventData: [...prevState.eventData, result.args]
}));
The problem with your code here. Is that the arrow function was never called :
{() => {
if (this.state.eventData[i].paramTwo) {
<span>Win</span>;
} else {
<span>Loose</span>;
}
}
}
This function can be reduced to the following (after applying the deconstructing seen in the below code) :
<span>{paramTwo ? 'Win' : 'Lose'}</span>
Next up, removing repetitions in your function by mapping it. By setting conditions at the right place and using ternaries, you can reduce your code to the following and directly include it the the JSX part of your render function :
render(){
return(
<div> //Could also be a fragment or anything
{this.state.allRecords || this.state.account === this.state.eventData[i].paramOne &&
this.state.eventData.map(({ paramOne, paramTwo, paramThree, paramFour, paramFive, paramSix }, i) =>
<div className="event-result-table-container" key={i}> //Don't forget the key like I just did before editing
<div className="result-cell">
{paramOne}
</div>
<div className="result-cell">
<span>{paramTwo ? 'Win' : 'Lose'}</span>
</div>
<div className="result-cell">
{paramThree.c[0]}
</div>
<div className="result-cell">
{paramFour.c[0]}
</div>
<div className="result-cell">
{paramFive.c[0] / 10000}
</div>
<div className="result-cell-last">
{paramSix.c[0]}
</div>
</div>
)
}
</div>
)
}
Finally, to only get the 20 first elements of your array, use slice :
this.state.eventData.slice(0, 20).map(/* CODE ABOVE */)
EDIT :
Sorry, I made a mistake when understanding the condition you used in your rendering, here is the fixed version of the beginning of the code :
{this.state.allRecords &&
this.state.eventData.filter(data => this.state.account === data.paramOne).slice(0, 20).map(/* CODE ABOVE */)
Here, we are using filter to only use your array elements respecting a given condition.
EDIT 2 :
I just made another mistake, hopefully the last one. This should ahve the correct logic :
this.state.eventData.filter(data => this.state.allRecords || this.state.account === data.paramOne).slice(0, 20).map(/* CODE ABOVE */)
If this.state.allRecords is defined, it takes everything, and if not, it checks your condition.
I cleaned up and refactored your code a bit. I wrote a common function for the repetitive logic and passing the looped object to the common function to render it.
Use Map instead of forloops. You really need to check this this.state.account === this.state.eventObj.paramOne statement. This could be the reason why you see only one item on screen.
Please share some dummy data and the logic behind unshift part(never do it directly on state object), we'll fix it.
getRecord = (eventObj) => (
<React.Fragment>
<div className="result-cell">
{eventObj.paramOne}
</div>
<div className="result-cell">
{eventObj.paramTwo ? <span>Win</span> : <span>Loose</span>}
</div>
<div className="result-cell">
{eventObj.paramThree.c[0]}
</div>
<div className="result-cell">
{eventObj.paramFour.c[0]}
</div>
<div className="result-cell">
{eventObj.paramFive.c[0] / 10000}
</div>
<div className="result-cell-last">
{eventObj.paramSix.c[0]}
</div>
</React.Fragment>
)
render() {
let allRecords;
if (this.state.allRecords) {
allRecords = <div>{this.state.eventData.map(eventObj => this.getRecord(eventObj)}</div>;
} else if (!this.state.allRecords) {
allRecords = <div>{this.state.eventData.map(eventObj => {
if (this.state.account === this.state.eventObj.paramOne) {
return this.getRecord(eventObj);
}
return null;
})}</div>;
}
return (<div className="event-result-table-container">{allRecords}</div>);
}
I was wondering if it is possible to programmatically assign and get refs in React. Suppose I wanted to go through a loop creating elements, giving them refs that consist of a name + an index. I know I can assign them like that using strings. However, the only way I know how to access refs consists of using this.refs.refname which, as far as I know, precludes me from doing something like this.refs.{refname + index}. Is there any way I can do something like this? The source code below should hopefully give you an idea of what I'm asking.
render = () => (<div className='row signature-group'>
<div className='col-md-1 col-xs-2'>
<b>{this.props.signerDescription}</b>
</div>
<div className='col-md-4 col-xs-7'>
{this.props.signers.map((signer, index) => <div className='text-with-line' key={index} ref={"sig" + index}>{signer}</div>)}
</div>
<div className='col-md-2 col-xs-3'>
{this.props.signers.map((signer, index) => {
return (index > 0 && this/*.refs.sig+index.value == whateverValue*/) ?
(<div className='text-with-line-long-name' key={index}>Date</div>) :
(<div className='text-with-line' key={index}>Date</div>);
})}
</div>
</div>)
Also, I've heard that using strings to assign refs is considered legacy. Is there any way to programmatically assign refs in a more up-to-date fashion?
Yes, you can use a ref callback to achieve this. The function passed as the ref attribute value will be passed the DOM node of the component once, after it is rendered:
applyRef = (index, ref) => {
this[`sig${index}`] = ref;
};
render = () => (
<div className="row signature-group">
<div className="col-md-1 col-xs-2">
<b>{this.props.signerDescription}</b>
</div>
<div className="col-md-4 col-xs-7">
{this.props.signers.map((signer, index) => (
<div className="text-with-line" key={index} ref={this.applyRef.bind(this, index)}>
{signer}
</div>
))}
</div>
<div className="col-md-2 col-xs-3">
{this.props.signers.map((signer, index) => {
return index > 0 && this[`sig${index}`].clientHeight > 0 ? (
<div className="text-with-line-long-name" key={index}>
Date
</div>
) : (
<div className="text-with-line" key={index}>
Date
</div>
);
})}
</div>
</div>
);
You can use bracket notation to create a new property on your class component (this) and then you access it with the same name (this.sig1, this.sig2).
String refs are deprecated and should no longer be used. Your refs are now applied directly to the component instance (this).
I'm fairly new to ReactJS. I am looking to get the value inside a <div> when contentEditable is set to true.
const listResults = this.state.results['1'].map((result) =>
<div key={result.toString()} contentEditable="true">
{result}
</div>
);
return (
<h1> listResults </h1>
<div> {listResults} </div>
)
I am currently outputting a list into pre-filled text-boxes which allows the user to edit them. I am looking to add in a button which once clicked captures the data inside all of the text-boxes. Can anyone point me in a direction on how to capture the changed data.
It may also be worth noting I am using ReactJS on the client side through a CDN.
To get value of editable div:
class App extends React.Component {
constructor(){
super();
this.state = {
arr: [1,2,3,4,5]
}
this.change = this.change.bind(this);
}
change(e, index){
let tmpArr = this.state.arr;
tmpArr[index] = e.target.textContent;
this.setState({arr: tmpArr})
}
render(){
console.log(this.state);
return (
<tr>
{this.state.arr.map((el, index) => <td key={index} id="test" onBlur={(e) => this.change(e, index)} contentEditable="true">{el}</td>)}
</tr>
);
}
}
https://jsfiddle.net/69z2wepo/84647/
One note, you can't return two elements on the same level:
return (
<h1> listResults </h1>
<div> {listResults} </div>
)
It should be wrapped like this:
return (
<div>
<h1> listResults </h1>
<div> {listResults} </div>
</div>
)