setting variables in a map function - reactjs

I have a function that returns this jsx mixed with some code like this:
showMedia = () => {
return (
<div>
{
<div id="mainContent">
{props.files.map((file) =>
const ext = fileExtension(file.name),
const icon = fileIcon(ext),
const isImg = isImage(ext),
<div key={file.id}>
<DisplayResults
fileId={file.id}
downloadName={file.downloadName}
fileTitle={file.title}
isImg={isImg}
icon={icon}
ext={ext}
/>
</div>
)}
</div>
}
</div>
);
}
In my editor, it's saying that it is expecting an '{' for the const variables I am setting after .map
Am I not using the correct syntax?
Thanks!

Since you don't have a function body {} for your arrow function, it is expecting an implicitly returned expression.
Give it a function body and declare your variables and return the JSX instead:
showMedia = () => {
return (
<div>
{
<div id="mainContent">
{props.files.map(file => {
const ext = fileExtension(file.name);
const icon = fileIcon(ext);
const isImg = isImage(ext);
return (
<div key={file.id}>
<DisplayResults
fileId={file.id}
downloadName={file.downloadName}
fileTitle={file.title}
isImg={isImg}
icon={icon}
ext={ext}
/>
</div>
);
})}
</div>
}
</div>
);
};

You have to add "return" in map function because map always expect to return something, so your problem can be solved by adding this
{props.files.map(file => {
return (
<div key={file.id}>
{/* something */}
</div>
);
})}
Hope this help

Related

Why it is showing unreachable code after return?

The statement after return (Where I am sending props to ProList , in the mapping section) is showing unreachable. I am still learning react. Can anyone help me in this regard?
import "./Workcard.css"
import React from 'react'
import ProList from "./ProList"
import projcarddata from "./ProlistData"
const Workcard = () => {
return (
<div className="work-container">
<h1 className="project-heading">Projects</h1>
<div className="project-container">
{
projcarddata.map((val,ind) =>
{
return
(
<ProList key={ind} imgsrc={val.imgsrc} title={val.title} text={val.text} view={val.view} source={val.source}/>
);
}
)
}
</div>
</div>
);
};
export default Workcard
`
This can be fixed in two ways
Way 1: remove the braces after the return
Workcard = () => {
return (
<div className="work-container">
<h1 className="project-heading">Projects</h1>
<div className="project-container">
{projcarddata.map((val, ind) => {
return <ProList key={ind} imgsrc={val.imgsrc} title={val.title} text={val.text} view={val.view} source={val.source} />;
})}
</div>
</div>
);
};
```
Way 2: remove the return statement and directly add the return value after the arrow
```
Workcard = () => {
return (
<div className="work-container">
<h1 className="project-heading">Projects</h1>
<div className="project-container">
{projcarddata.map((val, ind) => (
<ProList key={ind} imgsrc={val.imgsrc} title={val.title} text={val.text} view={val.view} source={val.source} />
))}
</div>
</div>
);
};
```
It's because of Automatic semicolon insertion .....
It would turn as return; ....
so instead turn it as below (see the above link for more info)
return(
....
)

Code duplication: how to avoid in Reactjs

Expectation: if the flag is true, then empty div "container" around div "content"
const Demo = () => {
const [flagABC] = useFlagFeature(true)
return (
<div className="featureflagoff"> style= {} onMouseEnter = {} //if feature flag is off || if feature flag is ON then empty div
<div className="content">
// huge code
<div>
</div>
);
}
how can i avoid copying the ("huge code") twice.
Assign the huge code to a variable and reference it.
const hugeCode = <div>...</div>
return (
<div className="featureflagoff">
<div className="content">
{hugeCode}
<div>
</div>
);
Assuming flagABC is the flag, you can do something like this:
const Demo = () => {
const [flagABC] = useFlagFeature(true)
return (
<div className={flagABC ? "" : "featureflagoff"}>
<div className="content">
// huge code
<div>
</div>
);
}

How to pass variables and functions to components in react?

I want to create a component and call each instance with individual values. Each component (<NewRanger .../>) should also use a different handleChangeFunction. I pass this as follows: handleChangeFunction={handleChangeEm100} where handleChangeEm100 is the individual name of the function. This should then be taken over within the component as onChange={{handleChangeFunction}}. But somehow it crashes for me without any concrete error. Am I doing something conceptually wrong here?
function Check() {
const [valueEm100, setValueEm100] = React.useState([96, 99]);
const handleChangeEm100 = (event, newValue, activeThumb) => {
..
};
function NewRanger({valueName, valueRange, valueNameRange, handleChangeFunction,
steps, minV, maxV}) {
return (
<>
<div className='Text-EM-main'>
<div className="Text-EM-0">
{valueName}:
</div>
<div className="Text-EM-1">
{{valueRange}[0]}
</div>
<div className="Text-EM-2">
<Slider
getAriaLabel={() => valueNameRange}
value={{valueRange}}
onChange={{handleChangeFunction}}
valueLabelDisplay="auto"
getAriaValueText={valuetext}
disableSwap
step={{steps}}
marks
min={{minV}}
max={{maxV}}
/>
</div>
<div className="Text-EM-3">
{{valueRange}[1]}
</div>
</div>
</>
)
}
return (
<>
<NewRanger
valueName={"EM100"}
valueRange={valueEm100}
valueNameRange={'em100 range'}
handleChangeFunction={handleChangeEm100}
steps={1} minV={90} maxV={110}/>
</>
)
First of all never define you components in other components. Move NewRanger to outside of the Check component. Also you are using extra {} in your code. Here is the updated code:
function NewRanger({valueName, valueRange, valueNameRange, handleChangeFunction,
steps, minV, maxV}) {
return (
<>
<div className='Text-EM-main'>
<div className="Text-EM-0">
{valueName}:
</div>
<div className="Text-EM-1">
{valueRange[0]}
</div>
<div className="Text-EM-2">
<Slider
getAriaLabel={() => valueNameRange}
value={valueRange}
onChange={handleChangeFunction}
valueLabelDisplay="auto"
getAriaValueText={valuetext}
disableSwap
step={steps}
marks
min={minV}
max={maxV}
/>
</div>
<div className="Text-EM-3">
{valueRange[1]}
</div>
</div>
</>
)
}
function Check() {
const [valueEm100, setValueEm100] = React.useState([96, 99]);
const handleChangeEm100 = (event, newValue, activeThumb) => {
..
};
return (
<>
<NewRanger
valueName={"EM100"}
valueRange={valueEm100}
valueNameRange={'em100 range'}
handleChangeFunction={handleChangeEm100}
steps={1} minV={90} maxV={110}/>
</>
)

while using map() function props.data is undefined

its shows data without map function in console
but whenever I use map function it shows props.data is undifned and also undifined in console
I have used the same code for another page and that works
const Test_Footer = (props) => {
console.log("ok", props.data)
const newvar =props.data.map((item) => {
return (
<>
<li>{item.data.id}</li>
</>
)
})
// console.log(newvar)
return (
<div>
<div class="main-content">
<footer className="footer">
<div className="review-checkbox"><input type="checkbox" /><label>Review</label></div>
<div className="question-nav">
<ul className="pagination">
{newvar}
</ul>
<button className="minimize-btn ml-10"><img src="images/minimize-btn.png" /></button>
</div>
</footer>
</div>
</div >
)
}
export default Test_Footer
const newvar = props && props.data && props.data.map((item) => {
return (
<>
<li>{item.data.id}</li>
</>
)
})

Why does React tell me unexpected token "."

I'm trying to display an json array on the screen but react tells me unexpected token "." I have searched around for 3 hours now but I can't figure out what is wrong or how to fix this. The other parts of the detail object all display correctly but for some reason the array just doesn't want to. I hope someone can help me with this problem.
the exact error I get is:
and the json in console log.
below is my code for the component.
function GeneDetail({ match }) {
useEffect(() => {
fetchDetails();
}, []);
const [detail, setDetail] = useState({})
//const [alleles, setAlleles] = useState([])
const fetchDetails = async () => {
const fetchDetails = await fetch(
'/api/get_genedetail?g='+match.params.genename+''
);
const detail = await fetchDetails.json()
setDetail(detail)
//setAlleles(detail.alleles)
}
console.log('alleles', detail.alleles)
return(
<div className="main-content">
<Container maxWidth="lg">
<div className="grid-container">
<div className="grid-title">
<h2>Gene: <i>{detail.geneName}</i></h2>
</div>
<div className="grid-subtitle">
<h3>Type: {detail.segmentFullName}</h3>
</div>
<div className="grid-alleles">
test
{detail.alleles ?
{detail.alleles.map(function (allele, i) {
return <div key={i}>
<h5>{allele.Number}</h5>
</div>
})}
: (<p>"No alleles found."</p>)}
</div>
</div>
</Container>
</div>
);
}
React errors can be confusing, the problem here is not that you have a dot there. Instead, you declare a variable expression in a variable expression, essentially like this:
{condition?{mappedData}:(alternative)}
You cannot declare an expression in an expression, you should've written it like this:
{detail.alleles ?
detail.alleles.map(function (allele, i) {
return <div key={i}>
<h5>{allele.Number}</h5>
</div>
})
: (<p>No alleles found.</p>)}
UpVote, if the solution works
function GeneDetail({ match }) {
useEffect(() => {
fetchDetails();
}, []);
const [detail, setDetail] = useState({})
//const [alleles, setAlleles] = useState([])
const fetchDetails = async () => {
const fetchDetails = await fetch(
'/api/get_genedetail?g='+match.params.genename+''
);
const detail = await fetchDetails.json()
setAlleles(detail.alleles)
}
console.log('alleles', detail.alleles)
return(
<div className="main-content">
<Container maxWidth="lg">
<div className="grid-container">
<div className="grid-title">
<h2>Gene: <i>{detail.geneName}</i></h2>
</div>
<div className="grid-subtitle">
<h3>Type: {detail.segmentFullName}</h3>
</div>
<div className="grid-alleles">
test
{alleles.length >= 0 ?
{alleles.map( (allele, i) => {
return <div key={i}>
<h5>{allele.Number}</h5>
</div>
})}
: (<p>"No alleles found."</p>)}
</div>
</div>
</Container>
</div>
);
}

Resources