Make onclick inside onclick in ReactJS - javascript

Hi guys I try to make onclick inside onclick, can I run clickdelete() without handleClick().
This is my code
<div
className="row-queue"
key={index}
onClick={() => handleClick(item, index)}
style={
index === myvideoIndex ? playingcolor : playingcolor2
}
>
<div className="column1-queue">{index + 1}</div>
<div className="column2-queue">{item.title}</div>
<div className="column3-queue">{item.singer}</div>
<div className="column4-queue">
<button
onClick={() => clickdelete(index)}
className="btn-delete"
>
<i className="fa fa-trash"></i>
</button>
</div>
</div>
Hope you guys understand what I'm asking :D

// Get a hook function
const {useState} = React
const Example = ({title}) => {
const [count, setCount] = useState(0);
return (
<div>
<div onClick={() => alert('parent')}>
With => e.stopPropagation();
<button onClick={(e) => {
e.stopPropagation();
alert('clicked button')
}}>
Click me
</button>
</div>
<div onClick={() => alert('parent')}>
Without => e.stopPropagation();
<button onClick={(e) => {
alert('clicked button')
}}>
Click me
</button>
</div>
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Example using Hooks:" />,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
yes it's possible use event.stopPropagation() so that event will not propagate to our parent div click handler.
<button onClick={(e) => {
e.stopPropagation()
clickdelete(index)
}} className="btn-delete">
<i className="fa fa-trash"></i>
</button>;

Related

if i click button then show this button id in reactJs

i create a onclick function const showContent=(id)=>{} and if i click the perticular button they will show id in const showContent = (id)=>{console.log(id)} like this .....
inside thisCart.jsx i rendering CartStyle.jsx using map method so this delete button inside here.
Cart
function Cart() {
const [data, setData] = useState([])
useEffect(() => {
const data = JSON.parse(localStorage.getItem('Cart'));
data.map(async (v) => {
try {
axios.get(`/cart/${v}`)
.then((res) => {
return setData((preV) => {
return [...preV, res.data]
})
})
.catch(e => { console.log(e) })
} catch (e) {
console.log(e);
}
})
}, [])
const showContent=(id)=>{
console.log('this is id', id)
}
return (
<>
<div className=" cartStyle row g-3">
<div className="left col-md-4">
<button className="btn btn-primary">Proceed to Buy</button>
</div>
</div>
<div className="right col-md-8 flex flex-wrap justify-around">
{
data.map((v, i) => {
return <CartStyle
key={i}
id={i}
title={v.title}
price={v.DiscountPrice}
img={v.image}
delete={showContent(i)}
/>
})
}
</div>
</div>
</>
)
}
export { Profile, Cart };
CartStyle
this is a CartStyle means i'm passing data from Cart.jsx to CarStyle.jsx using props
const CartStyle= (props) => {
return (
<>
<div style={{ width: '22em', height: '10em'}} className=" p-2 row g-3 card container rounded-2xl shadow py-2 my-3">
<button id="delBtn" onClick={props.delete} className="btn btn-primary my-2">Delete</button>
</div>
</div>
</>
)
};
export default CartStyle;
<CartStyle
key={i}
id={i}
title={v.title}
price={v.DiscountPrice}
img={v.image}
delete={(i) => showContent(i)} // or delete={showContent}
/>
// CartStyle
<button id="delBtn" onClick={() => props.delete(props.id)} className="btn btn-primary my-2">Delete</button>
You pass your id on your parent compoenent.Then you get the id in your child component as props.
const CartStyle= (props) => {
return (
<>
<div style={{ width: '22em', height: '10em'}} className=" p-2 row g-3
card container rounded-2xl shadow py-2 my-3">
<button id="delBtn" onClick={() => props.delete(props.id)}
className="btn btn-primary my-2">Delete</button>
</div>
</>
)
};
export default CartStyle
You need to assign a function to delete prop instead of invoking it directly.
Replace
<CartStyle
delete={showContent(i)}
/>
with
<CartStyle
delete={() => showContent(i)}
/>

how to use DOM element in React

I want to do getElementById to give css effect and click to slide function.
how do I use DOM in react? Thank you in advance.
function Auth() {
//this part needs to be fixed
const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('body');
signUpButton.addEventListener('click', () =>
container.classList.add('right-panel-active'));
signInButton.addEventListener('click', () =>
container.classList.remove('right-panel-active'));
Here are the classnames that might help you understand my code better.
return (
<div className ="auth">
<div className="body" id="body">
<SignUp className="test" />
<SignIn className="test" />
<div className="slide__body">
<div className="slides">
<div className="slide SignUp__left">
<p>Already have an account?</p>
<button className="slide__btn" id='signUp' > Sign In </button>
</div>
<div className="slide SignIn__right">
<p>Not a Member?</p>
<button className="slide__btn" id='signIn' > Sign Up </button>
</div>
</div>
</div>
</div>
</div>
)
}
I guess the propose to use React is that fact you should interact in the component state.
I suggest you use State in your component and add some according to some interaction
function App() {
const [mode, setMode] = React.useState();
const handleMode = (mode) => {
setMode(mode);
};
const containerClasses =
mode === "signUp" ? "body right-panel-active" : "body";
return (
<div className="auth">
<div className={containerClasses} id="body">
<SignUp className="test" />
<SignIn className="test" />
<div className="slide__body">
<div className="slides">
<div className="slide SignUp__left">
<p>Already have an account?</p>
<button
className="slide__btn"
id="signUp"
onClick={() => handleMode("signIn")}
>
{" "}
Sign In{" "}
</button>
</div>
<div className="slide SignIn__right">
<p>Not a Member?</p>
<button
className="slide__btn"
id="signIn"
onClick={() => handleMode("signUp")}
>
{" "}
Sign Up{" "}
</button>
</div>
</div>
</div>
</div>
</div>
);
}
You should avoid direct modification of the dom in React. React assumes that it is the only piece of code modifying the dom, and so it won't know about any changes you make. This opens up the possibility of bugs where react changes something on the dom that you don't expect, or doesn't change something you do expect. A simple piece of code like yours won't have these bugs, but best to learn the react way now so you don't run into these issues with more complicated code.
The react way to do this is to pass onClick props to the elements that need it, and to have a state variable which controls the class names. For example:
import React, { useState } from 'react';
function Auth() {
const [showPanel, setShowPanel] = useState(false);
return (
<div className="auth">
<div className={showPanel ? "body right-panel-active" : "body"}>
<SignUp className="test" />
<SignIn className="test" />
<div className="slide__body">
<div className="slides">
<div className="slide SignUp__left">
<p>Already have an account?</p>
<button
className="slide__btn"
onClick={() => setShowPanel(false)}
>
Sign In
</button>
</div>
<div className="slide SignIn__right">
<p>Not a Member?</p>
<button
className="slide__btn"
onClick={() => setShowPanel(true)}
>
Sign Up
</button>
</div>
</div>
</div>
</div>
</div>
);
}

How to implement conditional rendering in React Reusable Component?

I have this reusable component where I would like to pass a value through that if true: a button is returned and if the value is false: the button doesn't render. I can't figure out how to do this using reusable components. The boolean variable I want to use is displayButton where if it is true, then the button is rendered and if it is false then the button is not rendered.
const Test = ({ name, value, onClick, purchased, displayButton }) => {
return (
<div class="cardData">
<h5>{name}</h5>
<p>Cost: {value}</p>
//if display button = true, display this button, if false, button is not displayed
<button
type="button"
onClick={onClick}
class="btn btn-primary"
value={value}
name={name}
>
Purchase
</button>
<h4>{purchased}</h4>
</div>
);
};
export default Test;
Any help would very appreciated!
const Test = ({ name, value, onClick, purchased, displayButton }) => {
return (
<div class="cardData">
<h5>{name}</h5>
<p>Cost: {value}</p>
{displayButton &&
<button
type="button"
onClick={onClick}
class="btn btn-primary"
value={value}
name={name}
>
Purchase
</button>
}
<h4>{purchased}</h4>
</div>
);
};
export default Test;
if displayButton has the value of true it will render the button otherwise not
This will work.
const Test = ({ name, value, onClick, purchased, displayButton }) => {
return (
<div class="cardData">
<h5>{name}</h5>
<p>Cost: {value}</p>
{ displayButton &&
<button
type="button"
onClick={onClick}
class="btn btn-primary"
value={value}
name={name}
>
Purchase
</button>
}
<h4>{purchased}</h4>
</div>
);
};
export default Test;
You can create a ShowHide component which can be utilized for conditional-rendering instead of having logical operators in every JSX where you need to conditionally render.
// create a ShowHide component
const ShowHide = ({show,children} ) => show && children
// your Test component with the button wrapped in ShowHide
const Test = ({ name, value, onClick, purchased, displayButton }) => {
return (
<div class="cardData card col-6 m-3">
<h5>{name}</h5>
<p>Cost: {value}</p>
<ShowHide show={displayButton}>
<button
type="button"
onClick={onClick}
class="btn btn-primary"
value={value}
name={name}
>
Purchase
</button>
</ShowHide>
<h4>{purchased}</h4>
</div>
);
};
const root = document.getElementById('root');
ReactDOM.render(
<Test name="My Card"
value="250,000"
onClick={() => alert('clicked')}
purchased="Yes!"
displayButton={false}
/>,
root
)
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Good Luck...

scrollIntoView onClick reactjs

hello I have a few buttons and I want to scroll to them when clicked.
const [active, setActive] = useState(0);
useEffect(() => {
// I´m not using useRef. is there other way to automatically scroll to the element and stop at 0 0 of the page?
})
<div style={{height: '10000px'}} />
<button onClick={() setActive(1)}>button 1</button>
<button onClick={() setActive(2)}>button 2</button>
<button onClick={() setActive(3)}>button 3</button>
<div style={{height: '10000px'}} />
as you can see there´s a lot of scroll caused by those 2 divs. the idea is to scroll down and when you reach the buttons and click the one you need. the page scrolls to that button leaving it in the top of the page
image 1: scroll in random position
image 2: when you click on button 1
image 3: when you click on button 2
image 4: when you click on button 3
For scrolling react view to top there is a simple function.
use window.scrollTo(0, 0);
inside your code try this.
<button onClick={()=> window.scrollTo(0, 0) }>button 1</button>
edited:
I could come up with this solution after you edited your question.
import React, { useRef } from "react";
export default function App() {
const button1Ref = useRef();
const button2Ref = useRef();
const button3Ref = useRef();
const handleScroll = ref => {
window.scrollTo({
behavior: "smooth",
top: ref.current.offsetTop
});
};
return (
<div className="App">
<div style={{ height: "10000px" }} />
<div>
<button ref={button1Ref} onClick={() => handleScroll(button1Ref)}>
button 1
</button>
</div>
<div>
<button ref={button2Ref} onClick={() => handleScroll(button2Ref)}>
button 2
</button>
</div>
<div>
<button ref={button3Ref} onClick={() => handleScroll(button3Ref)}>
button 3
</button>
</div>
<div style={{ height: "10000px" }} />
</div>
);
}
Please try it out. Let me know if this is what you asked for.
Edited after question asked in comment for using single component with Ref and using that component in multiple numbers:
If you want to use a single component for button then try this,
import React, { useRef } from "react";
export default function App() {
return (
<div className="App">
<div style={{ height: "10000px" }} />
<MyButton>button 1</MyButton>
<MyButton>button 2</MyButton>
<MyButton>button 3</MyButton>
<div style={{ height: "10000px" }} />
</div>
);
}
const MyButton = props => {
const buttonRef = useRef();
const handleScroll = () => {
window.scrollTo({
behavior: "smooth",
top: buttonRef.current.offsetTop
});
};
return (
<div>
<button ref={buttonRef} onClick={handleScroll}>
{props.children}
</button>
</div>
);
};
Here you want to use an event handler.
const handleClick = (e) => {
// scrollIntoView logic and set state
}
<div onClick={handleClick}/>
//action
const goDown= (e) => {
const anchor = document.querySelector('#some-id')
anchor.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
// click to scroll
<Link onClick={goDown}>Choose Health</Link>
//element you want to scroll to
<div id='some-id'>
</div>

React mouseEnter event not working when on mapped children

I just want these child elements to show a remove button on mouseover...
console logging in handleMouseEnter shows that on render, ALL children fire the mouseEnter event. it seems stuck in a loop. debugging is next to impossible.
problems only arise when onMouseEnter and onMouseLeave are left in the code.
render(){
const handleMouseEnter = (tool) => this.setState({display : tool});
const handleMouseLeave = () => this.setState({display : "none"});
return (
<div>
<div className="search-result-background">
<div className="search-result-row row">
<div className="col-md-4">
</div>
<div className="col-md-4">
<form>
<TextFieldGroup className="find-tool-search-bar"
onChange= {this.checkToolExists}
value = {this.state.toolname}
field = 'toolname'
label = ''
error = {this.state.errors}
placeholder = "FIND IN FAVORITES"
/>
</form>
</div>
<div className="col-md-4">
<ButtonToolbar>
<DropdownButton noCaret onSelect={this.sort} bsSize="large" title="Sort by" id="dropdown-size-large">
<MenuItem eventKey="1">Name</MenuItem>
<MenuItem eventKey="2">Uploaded Date</MenuItem>
</DropdownButton>
</ButtonToolbar>
</div>
<h1 className="search-error">{this.state.errors}</h1>
<div className="col-md-12" >
{this.state.filteredTools.map((tool,i)=>
<div key ={i} className={"child " + tool.toolname } onMouseEnter={handleMouseEnter(tool.toolname)}
onMouseLeave={handleMouseLeave}> {this.state.display == tool.toolname ?
<button >remove?</button> : null}
<Link to={`/tools/${tool.id.substring(4)}`}>
<Thumbnail
className="thumb" src={logoImagePurple} alt="242x200">
<h3>{tool.toolname}</h3>
</Thumbnail>
</Link>
</div>
)}
</div>
</div>
</div>
</div>
)
}
}
The problem is this line:
onMouseEnter={handleMouseEnter(tool.toolname)}
You should change it to:
onMouseEnter={() => handleMouseEnter(tool.toolname)}

Categories