Conditional rendering and onClick event using ternary operator - reactjs

I am trying to show an alert onclick of an element that is conditionally rendered but the onclick event doesn't work i took the code out of the ternary operator and it worked but i cna't seem to find the reason why it didn't work in the ternary operator.
import React from 'react';
import HomeIcon from '../Images/home.svg'
import HomeIconBlue from '../Images/home-blue.svg';
function Menubar(props) {
const style = {
borderTop: "3px solid #2D79BB",
color: "#2D79BB",
}
return (
<div className="menu-bar">
<div className="home-icon">
{
(props.active === 'home') ?
<span style={style} onClick={alert('hey')}>
<img src={HomeIconBlue} alt="home" />
<p>Home</p>
</span> :
<span>
<img src={HomeIcon} alt="home" />
<p>Home</p>
</span>
}
</div>
)
}
export default Menubar

Try changing the onClick from
onClick={alert('hey')}
To
onClick={() => alert('hey')}

The element you kept the onClick event is not yet rendered keep it on the second element.
The one currently being rendered
return (
<div className="menu-bar">
<div className="home-icon">
{
(props.active === 'home') ?
<span style={style} >
<img src={HomeIconBlue} alt="home" />
<p>Home</p>
</span> :
<span onClick={alert('hey')}>
<img src={HomeIcon} alt="home" />
<p>Home</p>
</span>
}
</div>
)

Related

How to change text-overflow on Blueprintjs Suggest component in React?

I have a Suggest component that is rendered out like this:
<div class="bp4-popover-content">
<div>
<ul class="b4-menu">
<li>
<a>
<div class="bp4-fill bp4-text-overflow-ellipsis">
<div>Some text</div>
</div>
</a>
</li>
</ul>
</div>
</div>
By default, it uses text-overflow ellipsis, but i want to switch it to bp4-text-overflow-wrap. How can I achieve this in React? What I have so far:
const ItemSelect = Suggest.ofType<Items>();
<ItemSelect
fill
items={newUserItems}
itemListPredicate={filterItems}
itemRenderer={renderItem}
noResults={<MenuItem disabled={true} text="No results." />}
onItemSelect={(item, event) => {
setQuery(item.name);
item.isNew = false;
onItemSelect(item);
}}
popoverProps={{
minimal: true,
popoverClassName: `custom-class ${
isOpenLine ? "open-line-popover" : "non-open-line-popover"
}`,
}}
inputValueRenderer={() => query}
resetOnSelect={true}
resetOnQuery={true}
onQueryChange={(q, event) => {
if (event === undefined) {
setQuery(q);
}
}}
query={query}
inputProps={{ inputRef: inputRef }}
/>

find div inside a plugin with className and add another class to it in react

I want to find a div that has been rendered by react-date-range which has a className of rdrDateRangePickerWrapper and add another class to it. but currently, it's not working, is there any other way to do this?
this is the part of the code,
<div>
<i
role="button"
className="far fa-calendar-alt"
onClick={() => {
!openDistributionDatepicker && setOpenIngestDatepicker((prev) => !prev);
document
.getElementsByClassName("rdrDateRangePickerWrapper")
.classList.add(" another-class");
}}
/>
{openIngestDatepicker && (
<div className="z-intex999">
<DateRangePicker
onChange={(item) => setIngestDate([item.selection])}
showSelectionPreview={true}
moveRangeOnFirstSelection={false}
months={2}
ranges={ingestDate}
direction="horizontal"
/>
</div>
)}
</div>
Try below code:
document.querySelectorAll(".rdrDateRangePickerWrapper")
.forEach(element => element.classList.add('another-class'));

related to React js (props) css inline style

I want to more than one cards in different background color what i do ?
eg:
import React from "react";
import reactDom from "react-dom";
const BgColor=(props)=>{
return(
<>
<div className="main_div">
<div className="cards" >
<div className="card-side front" >
<div><span>C</span>opy<span>C</span>ode</div>
</div>
<div className="card-side back">
<div><i className="fas fa-copy fs-3" /><br />{props.code}</div>
</div>
</div>
</div>
</>
)
}
export default BgColor;
by pass value in app.js
and so on.....
please help me how to pass value inside the app.js
with this example is hard to to help you. Indeed, we don't know what your props object contains.
Let's assume your props contains
{
name: "toto",
code: "myCode"
}
In order to change background color based on props, you have multiples choices.
You can use dynamics classNames based on your props:
const BgColor=(props)=>{
return(
<>
<div className="main_div">
<div className="cards" >
<div className={`${props.name} card-side front`} >
<div><span>C</span>opy<span>C</span>ode</div>
</div>
<div className="card-side back">
<div><i className="fas fa-copy fs-3" /><br />{props.code}</div>
</div>
</div>
</div>
</>
)
}
See the <div className={${props.name} card-side front} > line. Go to css or scss file for this component and add a class selector inside of it.
In our example, it will be
.toto {
background: red
}
The second option is to inject directly the css inside your div.
Let's assume you send the desired background color inside your propos:
{
backgroundColor: "red",
code: "myCode"
}
In order to that, you have to do this
const BgColor=(props)=>{
return(
<>
<div className="main_div">
<div className="cards" >
<div className="card-side front" style={{backgroundColor: props.backgroundColor}}>
<div><span>C</span>opy<span>C</span>ode</div>
</div>
<div className="card-side back">
<div><i className="fas fa-copy fs-3" /><br />{props.code}</div>
</div>
</div>
</div>
</>
)
}
If you want to know more about css in React, you can check:
https://reactjs.org/docs/faq-styling.html, React.js inline style best practices, https://create-react-app.dev/docs/adding-a-stylesheet/
UPDATE
You can send an array of colors like <BgColor colors={["red", "blue"]} /> then in your BgColor component, you can map on your props like:
const BgColor=({colors})=>{
return (
<div className="main_div">
<div className="cards">
{colors.map((color, index) => {
return (
<div
className="card-side front"
style={{ backgroundColor: color }}
key={index}
>
<div>
<span>C</span>opy<span>C</span>ode
</div>
</div>
);
})}
</div>
</div>
);
}

How to make my functional Post component have certain linkable properties?

I'm new to React and haven't learned how to use databases and other functions as of yet and this is my first major learning React project. I'm trying to make my functional Post component link/route to a /profile/uniqueTweetId. Here is my Post component, to show you how I have set it up.
function Post({displayName,username,verified,text,image,avatar,comments,shares,likes,twitterId}) {
return (
<div className = "post">
<div className = "post__avatar">
<Avatar src={avatar} />
</div>
<div className = "post__body">
<div className = "post__header">
<div className = "post__headerText">
<h3>
{displayName} {""}
<span className = "post_headerSpecial">
{verified && <VerifiedUserIcon className="post__badge" />} #
{username}
</span>
</h3>
</div>
<div className = "post__headerDescription">
<p>{text}</p>
</div>
<img src= {image} alt= "" />
<div className = "post__footer">
<span className ="post__chatSpan"> <ChatBubbleOutlineIcon className = "post__chatStyling" fontSize="small" onClick={() => setCommentCount(commentCount + 1)} />
<span className = "post__chatFormating">{comments + commentCount} </span>
</span>
<span className ="post__repeatSpan"> <RepeatIcon className = "post__repeatStyling" fontSize="small" onClick={() => setRepeatCount(repeatCount + 1)} />
<span className = "post__repeatFormating">{shares + repeatCount}</span>
</span>
<span className ="post__favoriteSpan"> <FavoriteBorderIcon className = "post__favoriteStyling" fontSize="small" onClick={() => setLikeCount(likeCount + 1)} />
<span className = "post__favoriteFormating">{likes + likeCount}</span>
</span>
<PublishIcon fontSize="small" />
</div>
</div>
</div>
</div>
)
}
export default Post;
The problem arises when I render, the Post in my functional Feed component.
function Feed() {
return (
<Router>
<div className= "feed">
<Switch>
</Switch>
{/* Header */}
<div className= "feed__header">
<h2>Home</h2>
</div>
{/* TweetBox */}
<TweetBox />
{
listOfPosts.map(function (post) {
return (
< Post
displayName= {post.displayName}
username= {post.username}
verified= {post.verified}
text= {post.text}
avatar = "blah"
image = "blah"
comments = {post.comments}
shares = {post.shares}
likes = {post.likes}
twitterId ={post.twitterId}
/>
);
})
}
</div>
</Router>
)
}
export default Feed;
which listOfPosts is my array of hard coded "Post" prop variables that I'm currently looping through to render each post, so that in the future I could push the posts inside the array into a database when I'm ready. I'm struggling because I don't understand how to use React router in this context, because if I use Link inside the map function, All the props become a link, and I lose the functionality of my counters. I was hoping for ideas on how to attack this problem and to make my components work like an actual twitter post. Sorry for the long post it's my first StackOverflow question. Thank you again, any help is greatly appreciated!

How to show button while hover over box using react?

I am working on a project, it is an online shop in react.
I would like to make "Quick view" and "Add to cart" buttons visible only while hovering over the product box they're in. Also, they should be clickable. Code of the ProductBox below`
const ProductBox = ({ name, price, promo, stars }) => (
<div className={styles.root}>
<div className={styles.photo}>
{promo && <div className={styles.sale}>{promo}</div>}
<div className={styles.buttons}>
<Button variant='small'>Quick View</Button>
<Button variant='small'>
<FontAwesomeIcon icon={faShoppingBasket}></FontAwesomeIcon> ADD TO CART
</Button>
</div>
</div>
<div className={styles.content}>
<h5>{name}</h5>
<div className={styles.stars}>
{[1, 2, 3, 4, 5].map(i => (
<a key={i} href='#'>
{i <= stars ? (
<FontAwesomeIcon icon={faStar}>{i} stars</FontAwesomeIcon>
) : (
<FontAwesomeIcon icon={farStar}>{i} stars</FontAwesomeIcon>
)}
</a>
))}
</div>
</div>
<div className={styles.line}></div>
<div className={styles.actions}>
<div className={styles.outlines}>
<Button variant='outline'>
<FontAwesomeIcon icon={faHeart}>Favorite</FontAwesomeIcon>
</Button>
<Button variant='outline'>
<FontAwesomeIcon icon={faExchangeAlt}>Add to compare</FontAwesomeIcon>
</Button>
</div>
<div className={styles.price}>
<Button noHover variant='small'>
$ {price}
</Button>
</div>
</div>
</div>
);
Please follow the below code:
import React, {useState} from "react";
export default function ShowButtonHover() {
const [style, setStyle] = useState({display: 'none'});
return (
<div className="App">
<h2>Hidden Button in the box. Move mouse in the box</h2>
<div style={{border: '1px solid gray', width: 300, height: 300, padding: 10, margin: 100}}
onMouseEnter={e => {
setStyle({display: 'block'});
}}
onMouseLeave={e => {
setStyle({display: 'none'})
}}
>
<button style={style}>Click</button>
</div>
</div>
);
}
EDIT: made a codesandbox to make it easier https://codesandbox.io/s/stckovw-hideshow-hs3mh
A way to achieve this can be through these steps:
Add onMouseEnter and onMouseLeave handlers to the component you want to trigger the rendering of the buttons, so ProductBox in your case
Give the default class of your buttons a property of display = none
Switch the display to block for example when the event handlers are triggered.
If you are keeping a stateless component for your implementation:
const [display, setDisplay]=useState('notdisplayed');, with notdisplayed the default class with display=none
<div className={display}> on the components you want to hide/show
Call setDisplay in the onMouseEnter and onMouseLeave definition

Resources