Hi I want to render a string with looping logic behind it so I decided to put function that will return the string
function Leasing(){
let {idLeasingExact} = useParams()
const checkParam = () =>{
//return(idLeasingExact)
dropdownItems.map((item,index) => {
if(idLeasingExact == item.path){
console.log(idLeasingExact)
console.log(item.path)
console.log(item.title)
return(
item.title
)
}
})
}
return(
<div>
<h1>
{idLeasingExact ? checkParam() : "Leasing"
}
</h1>
</div>
)
}
export default Leasing;
here is the dropdown item
export const dropdownItems = [
{
title:'SMF',
path:'1',
cName:'dropdown-link'
},
{
title:'BFI',
path:'2',
cName:'dropdown-link'
},
{
title:'ADIRA',
path:'3',
cName:'dropdown-link'
}
]
I use param and that param will be used in function checkParam to return the result
the checkParam() shouldve return the title(SMF BFI ADIRA) as the result
for example if it's leasing/1 it shouldve return the title of SMF
or if it's leasing/2 it shouldve return the title of BFI
but it return null, althought the console log on the browser shows the right item.title just like the example
help appreciated I'm stuck here thanks
CodePudding user response:
So you're not wanting to actually do a map
. You gotta find
the item on dropdownItems
with path
equals to idLeasingExact
. Try changing your checkParam()
function to something like this:
const checkParam = () => {
const item = dropdownItems.find(x => x.path == idLeasingExact);
if (item) return item.title;
else {
// do whatever you want if path is not found, for example:
return 'No title found.'
}
}
What your code is doing, is some sort of a conditional mapping and the function checkParam()
is not actually returning something if you take a close look (the function inside the map does return the .title
, not the checkParam()
!)
CodePudding user response:
map() returns a list. checkParam() is not returning that list. Just add return to the function-
const checkParam = () =>{
return dropdownItems.map((item,index) => {
if(idLeasingExact == item.path){
return(
item.title
)
}
})
}
Also, you can add your JSX logic in checkParam itself like this-
const checkParam = () => {
return dropdownItems.map((item, index) => {
if (idLeasingExact == item.path) {
return <h1>{item.title}</h1>
} else {
return <h2>{"Leasing"}</h2>
}
})
}
return <div>{checkParam()}</div>
This will give you more control based on idLeasingExact value (e.g. conditional styling)