How to add a className to single .map item? - reactjs

I want to add className to a .map item, but only for the one which is clicked.
Tried useState ( {state ? "class" : ""} ) but it added class for all items inside my loop.
I also tried useRef but I learned that useRef does not cause re-render so result didn't update on screen.
example code:
{posts.map((post)=> {
return (
<div className=`PLACE FOR CLASS` key={post.id}>
{post.title}
<button onClick={()=> onclick event to add class}>add</button>
</div>
)
})}
So what is the way to add class only for item which is clicked in this case? ( I think I need to use Key but don't know how )

If you don't want to add this information to the main state (posts) you can create a separate list of selected ids, it'll be something like this (assuming you're using function components)
const [selectedPosts, setSelectedPosts]=useState([]);
...
{posts.map((post)=> {
return (
<div className={selectedPosts.includes(post.id) && "myClass"} key={post.id}>
{post.title}
<button onClick={()=> {setSelectedPosts(s => [...s, post.id])}}>add</button>
</div>
)
})}

Related

How do I pass a certain data onClick in React in this situation

Basically I have a loop that runs through "ScannedCrops" and each scannedcrop renders with a button which says "View More". I want to pass the id (Which is stored in ScannedCrop._id) and console.log that onClick.
This is the loop
<div className={styles.scannedCropsGrid}>
{
scannedCrops.map(ScannedCrop => {
return <div>
<div className={styles.center}>
<div className={styles.scannedCropsContent}>
<img src={ScannedCrop.image} alt="/" />
<div className={`${ScannedCrop.healthyBoolean ? styles.healthyPlant : styles.notHealthy}`}>
{
<p>{ScannedCrop.healthyBoolean ? "Healthy" : "Not Healthy"}</p>
}
</div>
<div className={styles.healthDesc}>
<p>{ScannedCrop.healthyBoolean ? "No Disease" : ScannedCrop.diseaseName}</p>
<p>||</p>
<p>{ScannedCrop.dateTime}</p>
</div>
<div className={styles.center}>
<button className={styles.viewMoreBtn}>
More Info
</button>
</div>
</div>
</div>
</div>
})
}
</div>
This is the onClick function in the same component.
const getId = () => {
}
What I want to do is that onClick I want to get the ScannedCrop._id and console.log it. I am kind of a beginner at this.
First of all you want to add a 'key' attribute to the parent in your map function. This can be either index or the ScannedCrop._id (if the later is always unique).
So it'll look like this:
...
{scannedCrops.map((ScannedCrop, index) => {
return <div key={index (or ScannedCrop._id if unique)} >
...
Lastly to answer your question, you first need to define your handler function and then pass it on to your button element inside the OnClick event. It should end up looking like this:
//it is a common practice to name your functions
//'handleClick', 'handleOnView' and so on. You can name it
//whatever you want
const handleGetId = (id) => console.log(id)
...
<div className={styles.center}>
<button
onClick={() => handleGetId(ScannedCrop._id)}
className={styles.viewMoreBtn}>
More Info
</button>
</div>
...
Hope that answers your question!

Render JSX from material-ui Button onClick

I'm trying to render JSX when a material-ui button is clicked. I'm logging to the console when clicking but cannot see any of the JSX getting rendered.
interface TileProps {
address?: string;
}
const renderDisplayer = (address: string) => {
console.log('Rendering address', address!);
if (typeof(address) == 'undefined' || address == '') {
return(<div className='error'><li>No address found</li></div>)
}
return(<AddressDisplayer address={address} />)
}
const Tile = (props: TileProps) => {
return(
<div className='tile'>
<ul>
<li>{props.address}</li>
</ul>
<Button variant='contained' onClick={() => {renderDisplayer(props.address)}}>Display</Button>
</div>
)
}
export default Tile;
I can see the console.log('Rendering address', address!); running when the button is clicked, but the JSX isn't getting rendered.
Could this be because I'm using React functional components instead of class components?
Your question is somehow unclear for me. If you want to render <div className='error'><li>No address found</li></div> based on typeof(address) == 'undefined' || address == '' condition, there is no need to click on the button and it's better to use conditional rendering. For example:
{!props.address ? (
<div className='error'><li>No address found</li></div>
) : (
<AddressDisplayer address={props.address} />
)}
But if you want to render your address component by clicking on the button, you should define a state and set it true when clicking on the button. Like this:
const [shouldShowAddress, setShouldShowAddress] = useState(false);
{shouldShowAddress && (
<>
{!props.address ? (
<div className="error">
<li>No address found</li>
</div>
) : (
<AddressDisplayer address={props.address} />
)}
</>
)}
<Button
variant="contained"
onClick={() => {
setShouldShowAddress(true)
}}
>
Display
</Button>
Please read about the Life cycle This not how react work onclick function
renderDisplayer is called and return JSX to onClick event you need to use state here to render the component with ternary oprator renderDisplayer fuction do setState so DOM will update

React - Generating different Icons within a map function

I have a sidebar components whose list items are generated inside of a map function (movie genres fetched from an api). I would like to have a different icon next to each of the movie genres but have been unable to figure out a way to create a different for each run of the map function.
My thoughts are
1st: make an array of the icons I would like to display, in the order that I would like them to display in.
const icons = [
"AiOutlineHome ",
"FaUserNinja",
"GiSwordman",
"GiBabyFace",
"FaLaughBeam",
"GiPistolGun",
"GiPineTree",
"GiDramaMasks",
"GiFamilyHouse",
"GiElfEar",
"GiScrollUnfurled",
"GiScreaming",
"GiMusicalNotes",
"GiMagnifyingGlass",
"FaRegKissBeam",
"GiMaterialsScience",
"GiHalfDead",
"GiGreatWarTank",
"GiCowboyBoot",
];
Then in my map function generate a different icon for each list item
{movieGenres.map((genre) => {
return (
<li key={genre.id} className="nav-text">
<button
className="genre-btn"
onClick={() => genreSelectionHandler(genre.id)}
>
*<GENERATE ICON HERE />*
<span className="nav-item-title">{genre.name}</span>
</button>
</li>
);
})}
Is it possible to pragmatically create components like this? So that I can avoid creating each list item individually if I want different icon.
You can just take the index of your genre to get the icon. The index is the second argument to the callback of your map() function:
{movieGenres.map((genre, idx) => (
<li key={genre.id} className="nav-text">
<button
className="genre-btn"
onClick={() => genreSelectionHandler(genre.id)}
>
<Icon icon={icons[idx]} />
<span className="nav-item-title">{genre.name}</span>
</button>
</li>
))}
The Icon component would render the icon depending on what kind of icons you are using.
EDIT:
As you want to use react-icons you need to import the actual icon components rather than just using strings:
import {AiOutlineHome} from "react-icons/ai";
import {FaUserNinja} from "react-icons/fa";
// ....
const icons = [
AiOutlineHome,
FaUserNinja,
// ...
];
And render them:
{movieGenres.map((genre, idx) => {
// must be a capitalized name in order for react to treat it as a component
const Icon = icons[idx];
return (
<li key={genre.id} className="nav-text">
<button
className="genre-btn"
onClick={() => genreSelectionHandler(genre.id)}
>
<Icon />
<span className="nav-item-title">{genre.name}</span>
</button>
</li>
)
})}

Unexpected Behavior After State Change in React Component

RenderImages = (): React.ReactElement => {
let selected = this.state.results.filter(x=>this.state.selectedGroups.includes(x.domain))
console.log(selected)
return(
<div className="results_wrapper">
{selected.map((r,i)=>{
let openState = (this.state.selectedImage==i)?true:false;
return(
<RenderPanel panelType={PanelType.large} openState={openState} title={r.domain+'.TheCommonVein.net'} preview={(openIt)=>(
<div className="result" onClick={openIt} style={{ boxShadow: theme.effects.elevation8}}>
<img src={r.url} />
</div>
)} content={(closeIt)=>(
<div className="panel_wrapper">
<div className="panel_content">{r.content}</div>
{this.RenderPostLink(r.domain,r.parent)}
<div onClick={()=>{
closeIt();
this.setState({selectedImage:2})
console.log('wtfff'+this.state.selectedImage)
}
}>Next</div>
<img src={r.url} />
</div>
)}/>
)
})}
</div>
)
}
When I change the state of 'selectedImage', I expect the variable 'openState' to render differently within my map() function. But it does not do anything.
Console.log shows that the state did successfully change.
And what is even stranger, is if I run "this.setState({selectedImage:2})" within componentsDidMount(), then everything renders exactly as expected.
Why is this not responding to my state change?
Update
I have tried setting openState in my component state variable, but this does not help either:
RenderImages = (): React.ReactElement => {
let selected = this.state.results.filter(x=>this.state.selectedGroups.includes(x.domain))
console.log(selected)
let html = selected.map((r,i)=>{
return(
<RenderPanel key={i} panelType={PanelType.large} openState={this.state.openState[i]} title={r.domain+'.TheCommonVein.net'} preview={(openIt)=>(
<div className="result" onClick={openIt} style={{ boxShadow: theme.effects.elevation8}}>
<img src={r.url} />
</div>
)} content={(closeIt)=>(
<div className="panel_wrapper">
<div className="panel_content">{r.content}</div>
{this.RenderPostLink(r.domain,r.parent)}
<div onClick={()=>{
closeIt();
let openState = this.state.openState.map(()=>false)
let index = i+1
openState[index] = true;
this.setState({openState:openState},()=>console.log(this.state.openState[i+1]))
}
}>Next</div>
<img src={r.url} />
</div>
)}/>
)
})
return(
<div className="results_wrapper">
{html}
</div>
)
}
https://codesandbox.io/s/ecstatic-bas-1v3p9?file=/src/Search.tsx
To test, just hit enter at the search box. Then click on 1 of 3 of the results. When you click 'Next', it should close the pane, and open the next one. That is what I'm trying to accomplish here.
#Spitz was on the right path with his answer, though didn't follow through to the full solution.
The issue you are having is that the panel's useBoolean doesn't update it's state based on the openState value passed down.
If you add the following code to panel.tsx, then everything will work as you described:
React.useEffect(()=>{
if(openState){
openPanel()
}else{
dismissPanel();
}
},[openState, openPanel,dismissPanel])
What this is doing is setting up an effect to synchronize the isOpen state in the RenderPanel with the openState that's passed as a prop to the RenderPanel. That way while the panel controls itself for the most part, if the parent changes the openState, it'll update.
Working sandbox
I believe it's because you set openState in your map function, after it has already run. I understand you think the function should rerender and then the loop will run once more, but I think you'll need to set openState in a function outside of render.
The problem is that even though you can access this.state from the component, which is a member of a class component, there's nothing that would make the component re-render. Making components inside other components is an anti-pattern and produces unexpected effects - as you've seen.
The solution here is to either move RenderImages into a separate component altogether and pass required data via props or context, or turn it into a normal function and call it as a function in the parent component's render().
The latter would mean instead of <RenderImages/>, you'd do this.RenderImages(). And also since it's not a component anymore but just a function that returns JSX, I'd probably rename it to renderImages.
I tire to look at it again and again, but couldn't wrap my head around why it wasn't working with any clean approach.
That being said, I was able to make it work with a "hack", that is to explicitly call openIt method for selectedImage after rendering is completed.
RenderImages = (): React.ReactElement => {
let selected = this.state.results.filter((x) =>
this.state.selectedGroups.includes(x.domain)
);
return (
<div className="results_wrapper">
{selected.map((r, i) => {
let openState = this.state.selectedImage === i ? true : false;
return (
<RenderPanel
key={i}
panelType={PanelType.medium}
openState={openState}
title={r.domain + ".TheCommonVein.net"}
preview={(openIt) => {
/* This is where I am making explicit call */
if (openState) {
setTimeout(() => openIt());
}
/* changes end */
return (
<div
className="result"
onClick={openIt}
style={{ boxShadow: theme.effects.elevation8 }}
>
<img src={r.url} />
</div>
);
}}
content={(closeIt) => (
<div className="panel_wrapper">
<div className="panel_content">{r.content}</div>
{this.RenderPostLink(r.domain, r.parent)}
<div
onClick={() => {
closeIt();
this.setState({
selectedImage: i + 1
});
}}
>
[Next>>]
</div>
<img src={r.url} />
</div>
)}
/>
);
})}
</div>
);
};
take a look at this codesandbox.

Target specific child inside React loop with refs and state onClick

I've got a mobile nav menu with a couple dropdown menus:
/* nav structure */
/about
/portfolio
/services
/service-1
/service-2
contact
etc..
I'm creating this menu dynamically with a loop in my render function.
I've set up a state variable to assign a class to the active dropdown menu. I'm using an onClick event/attribute on the trigger element (a small arrow image) to apply an active class to the respective dropdown menu. Kinda...
const myNavMenu = () => {
const [isSubMenuOpen, toggleSubMenu] = useState(false)
return (
<nav id="mainNav">
<ul>
{navItems.items.map((item, i) => (
<li key={i} className={
(item.child_items) !== null ? 'nav-item has-child-items' : 'nav-item'}>
<Link to={item.slug}>{item.title}</Link>
{(item.child_items === null) ? null :
<>
<img className="arrow down" src={arrowDownImg} onClick={() => toggleSubMenu(!isSubMenuOpen)} />
{printSubMenus(item)}
</>
}
</li>
))}
</ul>
</nav>
)
}
/**
* Prints nav item children two levels deep
* #param {Obj} item a navigation item that has sub items
*/
function printSubMenus(item) {
return (
<ul className={(isSubMenuOpen.current) ? "sub-menu sub-menu-open" : "sub-menu"}>
{item.child_items.map( (childItem, i) => (
<li className="nav-item" key={i}>
<Link to={childItem.slug}>{childItem.title}</Link>
{(childItem.child_items === null) ? null :
<>
<ul className="sub-sub-menu">
{childItem.child_items.map( (subItem, i) => (
<li className="sub-nav-item" key={i}>
<img className="arrow right" src={arrowRight} alt={''} />
<Link to={subItem.slug}>{subItem.title}</Link>
</li>
))}
</ul>
</>
}
</li>
))}
</ul>
)
}
}
*<Link> is a Gatsby helper component that replaces <a> tags.
The issue is that when I click my trigger, the active class is being applied to both (all) sub-menus.
I need to insert some sort of index (or Ref) on each trigger and connect it to their respective dropdowns but I'm not quite sure how to implement this.
I was reading up on useRef() for use inside of function components. I believe that's the tool I need but I'm not sure how to implement it in a loop scenario. I haven't been able to find a good example online yet.
Thanks,
p.s. my functions and loops are pretty convoluted. Very open to refactoring suggestions!
Move sub-menu to a new react component and put all the related logic in there (applying class included).

Resources