How to blur out an entire webpage when a button is clicked - javascript

I'm setting up a one-page website with react.js, html, and scss. I am struggling to have the entire website have a blur effect or fade when a button is clicked (this will be later used for loading animations). What commands can I use to get this blur when a button is pressed?
render() {
return (
<div className="App">
<div className="top-bar">
<div className="title">poem</div>
<img className="logo" src="./logo.png" />
</div>
<div className="container">
<div className="sloganLineOne">Poem Theme</div>
<div className="sloganLineTwo">Detector</div>
<textarea
className="inputField"
placeholder="Please Enter Your Poem Here..."
/>
<button className="button" onClick={this.fadeOut}>
Enter
</button>
<img className="leftTriangle" src="./leftSideTriangle.png" />
<img className="rightTriangle" src="./rightSideTriangle.png" />
</div>
</div>
)
}
fadeOut = () => this.setState({ fadingOut: true })
}
I expect the entire page to be blurred or look like it when the button is clicked.

All you have to do is apply the style to your parent div and you should be good to go! Give this a shot
class App extends React.Component {
state = { fadingOut: false }
fadeOut = () => this.setState({fadingOut: true});
render() {
return (
<div className="App" style={this.state.fadingOut ? {filter: 'blur(2px)'} : undefined }>
<div className="top-bar">
<div className="title">
poem
</div>
</div>
<div className="container">
<div className="sloganLineOne">Poem Theme</div>
<div className="sloganLineTwo">Detector</div>
<textarea className="inputField" placeholder="Please Enter
Your Poem Here..."></textarea>
<button className="button" onClick={this.fadeOut}>Enter</button>
<img className="leftTriangle" src="./leftSideTriangle.png"/>
<img className="rightTriangle" src="./rightSideTriangle.png"/>
</div>
</div>
);
}
}
See it in action!

Related

How do I use Toggle method in Reactjs ? I have added sandbox link at the bottom

In this code, I want to toggle active class to icons div, I watched some youtube videos and they showed this method which is not what I want, this method does not add activeclass to a particular div it adds active class to every div that has icons class. I want whenever someone click onto the div active class should be added into it and when clicked again that class should get removed.
export default function Site() {
const [notActive, setActive] = useState(false);
const switchActive = () => {
notActive ? setActive(false) : setActive(true);
};
return (
<div id="container">
<nav id="navbar">
<a href="j" className="link">
Buzzify
</a>
<a href="f">
<FaRegUserCircle className="user-icon" />
</a>
</nav>
<div id="playlist-container">
<div id="playlist">
<div
className={notActive ? "icons active" : "icons"}
onClick={switchActive}
>
<BsCloudRain />
<VolSlider />
</div>
<div
className={notActive ? "icons active" : "icons"}
onClick={switchActive}
>
<GiForest />
</div>
<div className="icons">
<MdOutlineWaterDrop />
</div>
<div className="icons">
<BiWind />
</div>
<div className="icons">
<GiCampfire />
</div>
<div className="icons">
<GiThreeLeaves />
</div>
<div className="icons">
<BsMoonStars />
</div>
<div className="icons">
<BiWater />
</div>
<div className="icons">
<BiTrain />
</div>
<div className="icons">
<BiCoffeeTogo />
</div>
<div className="icons">
<FaFan />
</div>
<div className="icons">
<DiDigitalOcean />
</div>
<div className="icons">
<GiWaterfall />
</div>
<div className="icons">
<FaPlane />
</div>
<div className="icons">
<IoIosPlanet />
</div>
<div className="icons">
<GiOctopus />
</div>
</div>
</div>
</div>
);
}
CodeSandbox.io
You have two options in order to solve this:
1- You need a state for each icon that keeps track of if you clicked them or not. This could be done by making a React component that represents an icon and then use it to in your Site component:
export default function MyIcon({icon}) {
const [isActive, setIsActive] = useState(false)
return <div className={isActive ? "icons active" : "icons"}
onClick={() => {setIsActive(!isActive)}}>
{icon}
</div>
}
You can then use this component in Site() like this:
<MyIcon icon={<CertainIcon/>} />
2- You can programmatically toggle the classname "active" using the onClick event without relying on a state like this:
<div className="icons"
onClick={(event) => {event.currentTarget.classList.toggle('active')}}>
<CertainIcon/>
</div>
you should manage state per Icon like
const IconWithState = ({children}) => {
const [isActive, setIsactive] = useState(false)
const toggle = () => setIsactive(curr => !curr)
return (
<div
className={active ? "icons active" : "icons"}
onClick={toggle}
>
{children}
</div>
)
and then use it like
...
<div id="playlist-container">
<div id="playlist">
<IconWithState>
<BsCloudRain />
<VolSlider />
</IconWithState>
<IconWithState>
<GiForest />
</IconWithState>
....

React - Prevent child re-rendering in map

I have a re-render issue with a slider which appears in every element from a map.
const Attractions = () => {
const [slide, setSlide] = useState(0)
const handleSlider = (direction) => {
if(direction === "right"){
setSlide(slide + 1)
}else{
setSlide(slide - 1)
}
}
const translation = slide * - 110
return (
<div className="attractions">
<Navbar />
<Header nav={"attractions"}/>
<div className="attractionsContainer">
<div className="attractionsWrapper">
<div className="left">
</div>
<div className="right">
{attractionList.map(attraction => (
<div className="attractionWrapper" key={attraction.id}>
<div className="top">
<div className="topLeft">
<img src="https://holidaystoswitzerland.com/wp-content/uploads/2019/09/Lauterbrunnen.jpg.webp" alt="" className="avatarImg"/>
</div>
<div className="topRight">
<div className="title">{attraction.name}</div>
<div className="location"><LocationOnOutlinedIcon/>{attraction.location.city}, {attraction.location.country}</div>
</div>
<div className="moreInfo">
<MoreVertOutlinedIcon/>
</div>
</div>
<div className="middle">
<div className="sliderWrapper">
{slide > 0 &&
<div className="left" onClick={()=>handleSlider("left")}>
<ArrowBackIosNewOutlinedIcon style={{fontSize: "30px"}}/>
</div>
}
<div className="slider" style={{transform: `translateX(${translation}%)`}}>
{attraction.img.map(img =>(
<img src={img} alt="" />
))}
</div>
{slide < 2 &&
<div className="right" onClick={()=>handleSlider("right")}>
<ArrowForwardIosOutlinedIcon style={{fontSize: "30px"}}/>
</div>
}
</div>
</div>
<div className="bottom">
<div className="interactions">
<FavoriteBorderOutlinedIcon className="actionBtn"/>
<ChatBubbleOutlineOutlinedIcon className="actionBtn"/>
<CheckCircleOutlineRoundedIcon className="actionBtn"/>
<AddCircleOutlineOutlinedIcon className="actionBtn" />
</div>
<div className="description">
{attraction.description}
</div>
<div className="comments">
{attraction.comments.map(comment =>(
<div className="commentItem">
<h4>{comment.user}</h4>
<span>{comment.comment}</span>
</div>
))}
</div>
</div>
</div>
))}
</div>
</div>
</div>
<Footer />
</div>
)
}
When i get more elements from the attractionList array, whenever i click on the left or right arrow to go to the next slide, all of the sliders from the list will do the same. I figured out that i should use something so that the slide is set only based on the item from the map, but honestly i have no idea how.
If you want them to behave differently, then the attraction object should have its own slide variable and setSlide method. That way you can just put:
onclick = {() => attraction.setSlide(attraction.slide + 1)}

ReactJs force input focus on div button click not working

I'm working on a modal in react where I have to click a button outside an input element and focus the input element and change the value. I set the input element to be disabled on default and for the edit button to remove the disabled property and then focus the element. the element is not getting visible focused neither is the disabled property being removed. It looks like it happens in a split second and then returns back to normal because whenever I check if the element is being focused on my console it displays true but It's not being visible focused.
below is my code
EDIT FUNCTION
const [editState,setEditState] = useState(null)
const editCatName = (e,id)=>{
e.stopPropagation();
setEditState({...editState,id: categories[id].id})
setActiveButton('editcatname');
let row = document.querySelectorAll('.cat-row')[id].querySelector('input');
console.log('row',row)
row.classList.remove('pointer');
row.value='Row value set'
row.hasAttribute('disabled') && row.toggleAttribute('disabled')
row.focus();
console.log(row.value)
}
const [activeButton,setActiveButton] = useState('newproduct');
const ProductCategoryModal = ()=>{
return(
<div
onClick={()=>{setCategoryModal(false)}}
className="_modal fixed " style={{zIndex:'100'}} >
<div
onClick={e=>e.stopPropagation()}
className='wytBg boxRad paddBoth sectPad relative'>
<div>
<div className="flexBtw">
<h3 className="head flexAl">Product Categories</h3>
<div className='head'> <AiOutlinePlus/> </div>
</div>
</div>
<GridStyle className='nestM' gridp='45% 55%' gap='0em'>
<Scrolldiv className='' measure='300px'>
{
categories && categories.length?
categories.map((ctg,key)=>
ctg.name !=='Others' &&
<div key={key}
onClick={(e)=>
fixCategoryDetail(ctg.id,e)
}
className={`cat-row cursor rowws flexBtw ${ key===0 && 'rows-
top'}`}>
<div>
<input
defaultValue={ctg.name}
// disabled
style={{maxWidth:'180px'}}
className={'categoryInput pointer '+ key}
onChange={e=>setEditState({
id:ctg.id,
value:e.target.value
})}
onBlur={e=>{
e.target.value=ctg.name
}}
/>
{/* {ctg.name} */}
</div>
<div className="smallflex hashEdit">
<div>
<BiEditAlt
className='cursor'
FUNCTION TO FOCUS ELEMENT IS HERE
onClick={e=>editCatName(e,key)}
/>
</div>
{
!products.find(prod=>prod.category ===ctg.id) &&
<div className='hash'> <CgClose className='cursor'/> </div>
}
</div>
</div>
):null
}
</Scrolldiv>
<Scrolldiv measure='300px' className='secondRow paddBoth'>
{
categoryDetail.length?
<div className=" search flexC">
<div>
<SearchInputBox
icon={ <CgSearch style={{width:30}} />}
padLeft={'10px'}
className='searchInput smalltxt'
inputPadding='0.5em 0.6em'
// onchange={filterByStarts}
iconPosition
summary='Type or search a product'
options=
{products.filter(prod=>
prod.category===3).map(prod=>prod.name)}
inputClassName={'searchInput smalltxt'}
pad='0'
/>
<div className="nestM flex">
<div measure='150px' >
{
categoryDetail.length?
categoryDetail.map((ctg,key)=>
ctg.category !== 3 &&
<div key={key} className=
{`doubleflex flexBtw smalltxt
itemunits ${key!==0 &&
'smallM'} `}>
<div>{ctg.name}</div>
<div>
<CgClose onClick=
{()=>removeProductFromCategory
(ctg.id,ctg.name)}
className='cursor'/>
</div>
</div>
):null
}
</div>
</div>
</div>
</div>
:null
}
</Scrolldiv>
</GridStyle>
<div className="section flexC">
<button style={{maxWidth:'70%'}}
onClick={()=>
activeButton==='newproduct'?removeProductFromCategory():
activeButton==='addcategory'?createNewCategory():
editCategoryName()}
className="submit-button category-submit">
Update
</button>
</div>
</div>
</div>
)
}

How to change color icons in react after onClick

export default function Post({post}) {
const [like,setLike] = useState(post.like)
const [islike,setIslike] = useState(false)
const handler=()=>{
setLike(islike? like-1:like+1 )
setIslike(!islike)
}
return (
<>
<div className="postcontainer">
<div className='postwrapper'>
<div className="postTop">
<div className="topleft">
<img className="images" src= {Users.filter((u)=> u.id === post.userId)[0].imagesProfile} alt="profile" />
<span className="names"> {Users.filter((u)=> u.id === post.userId)[0].userName} </span>
<span className="dates"> {post.date}</span>
</div>
<div className="topzRight">
<MoreVert />
</div>
</div>
<div className="postcenter">
<span className='text'>{post.descrip}</span>
<img className="imagepost" src={post.imagesPost} alt="newpost" />
</div>
<div className="postbotton">
<div className="postbottonLeft">
<LocationOnIcon className="icon" />
<FavoriteIcon className="icon" onClick={handler}/>
<span className='counter' > {like} People liked it</span>
</div>
<div className="postbottonRight">
<span>{post.comment} comments</span>
<SmsOutlined className="iconcomment" />
</div>
</div>
</div>
</div>
</>
)
First, you should try to talk more about what you want to do in the code instead of just putting the question in the title and putting the code as the body.
Second, if you want some HTML element to have a different color based on when you clicked it or not, you could make a CSS class for each state you want, so one class could be .isLiked and the other can be .isNotLiked with each one having a different color. Then in your code, you can have a conditional on the className attribute for the HTML element to decide what it should be based on a conditional.
Eg: className={isLiked ? 'isLiked' : 'isNotLiked'}

How to dynamically render the user data in a component on button click in React

I'm new in React and got stuck on how can I achieve this.
After the user fills the field CEP from the first card and click on the button 'Gravar Dados', it shows a second card with all the information from the first card.
Template Picture:
New Result Picture:
What I need is dynamically create another card, under the second card with new info from the first card.
This is what I've done so far.
I have this component DadosPessoais.js which is the second card in the Template Picture:
render() {
return (
<div className="card shadow mt-5" >
<div className="card-header">
<span>Dados Pessoais </span>
</div>
<div className="card-body">
<div className="row">
<div className="col-4">
<div>
<span>Cep: <strong>{this.props.cep}</strong></span>
</div>
<div>
<span>Bairro: <strong>{this.props.bairro}</strong></span>
</div>
</div>
<div className="col-5">
<div>
<span>Rua: <strong>{this.props.rua}</strong></span>
</div>
<div>
<span>Cidade: <strong>{this.props.cidade}</strong></span>
</div>
</div>
<div className="col-3">
<div>
<span>UF: <strong>{this.props.uf}</strong></span>
</div>
</div>
</div>
</div>
</div>
);
}
In my Home.js I have a form with onSubmit that calls mostrarDadosPessoais function:
Function:
mostrarDadosPessoais(e) {
e.preventDefault();
this.setState({
listaDados: this.state.listaDados.concat({
cep: e.target.value,
rua: e.target.value,
bairro: e.target.value,
cidade: e.target.value,
uf: e.target.value,
}),
});
}
And my input components UserInput, Should it be like this?:
<div className="col-3">
<UserInput name="Rua" Label="Rua" Id="Rua" value={this.state.rua} Disabled />
</div>
<div className="col-3">
<UserInput name="Bairro" Label="Bairro" Id="Bairro" value={this.state.bairro} Disabled />
</div>
<div className="col-3">
<UserInput name="Cidade" Label="Cidade" Id="Cidade" value={this.state.cidade} Disabled />
</div>
<div className="col-1">
<UserInput name="UF" Label="UF" Id="UF" value={this.state.uf} Disabled />
</div>
And to show the result card I've done this:
<div className="col-md-4">
{this.state.listaDados.length === 0
? null
: this.state.listaDados.map((lista) => (<DadosPessoais {...lista} />))}
</div>
This is my state:
this.state = {
listaCidade: [],
listaDados: [],
}
Any ideas on how can I create another component and keep the values from the first one?
Thank you.
If I understand well, you need a list of elements, displayed on the right, that will show user-entered data. You need the user to be able to enter many addresses through the form on the left, and you want each address to display on the right.
I would solve this with a component that contains state for all the elements you need to display in an array that you update on a form submit event, because that's an easy event to work with when you have forms with lots of fields. You can grab the values of the components through the event object e.
class StateContainer extends Component {
constructor() {
super(props);
this.state = {
addresses: [],
}
}
mostrarDadosPessoais(e) {
e.preventDefault();
this.setState({
listaDados: this.state.listaDados.concat({
cep: e.target.cep.value,
rua: e.target.rua.value,
// etc, etc
}),
})
}
render() {
return (
<div>
<form handleSubmit={this.mostrarDadosPessoais}>
{/* left-side form */}
<input name="msg" />
<button type="submit"></button>
</form>
<div>
{/* right-side list of elements */}
{this.state.addresses.length === 0
? null
: this.state.addresses.map(
(address) => (<DadosPessoais {...address} />)
)
}
</div>
</div>
);
}
}

Categories

Resources