click handler not toggling state - javascript

I'm trying to create a simple app where if you click on a button, a modal overlay appears, and if you click on the 'x' in the modal it disappears.
I made a component for my button, called ShowOffer, and I have an onclick on it which toggles the boolean value of modalVisible, which is a piece of state.
However, nothing happens when I click on it.
I made another button element with the same onclick, and it seems to work fine.
Here is a code sandbox

You are adding onClick on the ShowOffer component, but here you are just passing it as a prop in it.
<ShowOffer display={"block"} onClick={toggleVisibility} />
is same as
React.createElement(ShowOffer, {
display: "block",
onClick: toggleVisibility
});
Under the hook, you are just passing an argument to a function
You have to add onClick event on the button in ShowOffer component as:
Live Demo
<button
style={{ display: `${display}` }}
onClick={toggleVisibility}
className="show-offer"
>
Show Offer
</button>
and you have to pass the toggleVisibility callback to ShowOffer as:
<ShowOffer display={"block"} toggleVisibility={toggleVisibility} />

This is the simple logic. Your ShowOffer component is not identify the onclick event and this component's button is not have any event handlers. So you just pass the event or directly pass the function name for access the event. Passing props name is the important one.
<ShowOffer display={"block"} onClick = {toggleBox}/>
export default function ShowOffer({ display, onClick}) {
return (
<button style={{ display: `${display}` }} className="show-offer" onClick={onClick}>
Show Offer
</button>
);
}
or
<ShowOffer display={"block"} toggleBoxFunct = {toggleBox}/>
export default function ShowOffer({ display, toggleBoxFunct }) {
return (
<button style={{ display: `${display}` }} className="show-offer" onClick={toggleBoxFunct}>
Show Offer
</button>
);
}

You can use concept of Callbacks,
App.js, make following changes,
pass toggleVisibility={toggleVisibility} as props, no need to mention onClick at component but at button
return (
<div className="App">
<Modal display={modalVisible ? "flex" : "none"} />
<ShowOffer display={"block"} onClick={toggleVisibility} toggleVisibility={toggleVisibility}/>
<button onClick={toggleVisibility}>Button</button>
</div>
);
ShowOffer.js, props passed function, call that function here with onclick,
import React from "react";
import "./ShowOffer.css";
export default function ShowOffer({ display, toggleVisibility }) {
return (
<button style={{ display: `${display}` }} onClick={toggleVisibility} className="show-offer">
Show Offer
</button>
);
}
working solution is here, https://codesandbox.io/embed/modal-overlay-tnis9?fontsize=14&hidenavigation=1&theme=dark

Related

show more and show less dinamicaly for each div

when I click the particular show more button the content should be displayed, the condition is the whole component should not re-rendering
I have used a useState when I clicked the button it is re-rendering the whole component
it is taking a long time to re-render every div
give an easy solution for this.
const [arr,setmarr] =useState([])
const oncl=(e)=>{
setarr((prev)=>[...prev,e.target.value])
}
return{
divarray.map((i,j)=>{
{console.log("tdic)")}
return(
<Commentbox divarr={arr[j]} value={j} oncl={(e)=>oncl(e) } />
)
}
}
Commentbox component
return
<div>
div{j}
// some icons here
{divarr && <div> right side div </div>}
<button onClick={(e)=>{oncl(e)}} value={j} >see more</button >
</div>
before onClick on showmore
after showmore button has been clicked on the second div
you should change each box to a component to solve this problem.
make that component with class base component because you need getSanpShotBeforeUpadte.
getSanpShotBeforeUpadte: you can control your component's render with this method.dont forget this method will give you nextProps,nextState and snapshot as parameter
class Box extends Component{
state = {
// more
showMore: false,
}
getSnapshotBeforeUpdate(nextProps,nextState){
// OTHER CONDITIONS
if(nextState.showMore !== this.state.showMore) return true
return false
}
render(){
return (
<div>
{/* CODE ... */}
<div style={{display: this.state.showMore ? 'block' : 'none'}}>
HERE IS A TEXT
</div>
<button onClick={()=>this.setState({showMore: !this.state.showMore})}>show more</button>
</div>
)
}
}

Get getAttribute from button and toggle class name to body react hooks

i want to improve my code, with several buttons that has custom class names (attr), when clicked should add to body tag (toggle), now is adding the first button only because for ("button")[0] but should work for each button
import React, { useState, useEffect } from "react"
function Test() {
const [isClass, setIsClass] = useState(false)
useEffect(() => {
const x = document.getElementsByTagName("button")[0].getAttribute("custom-class")
document.body.classList.toggle(x, isClass)
}, [isClass])
return (
<>
<button custom-class='test1' onClick={() => setIsClass(!isClass)}>
Setting test1 className
</button>
<button custom-class='test2' onClick={() => setIsClass(!isClass)}>
Setting test2 className
</button>
</>
)
}
export default Test
Thanks
Please use this code.
let oldStyle = "";
const handleClick = (index) => {
const x = [...document.getElementsByTagName("button")].map(value => value.getAttribute("custom-class"));
document.body.classList.contains(x[index]) ? document.body.classList.remove(x[index]) : document.body.classList.add(x[index]);
if(document.body.classList.length > 1) document.body.classList.replace(oldStyle, x[index]);
oldStyle = x[index];
}
return (
<>
<button custom-class='test1' onClick={() => handleClick(0)}>
Setting test1 className
</button>
<button custom-class='test2' onClick={() => handleClick(1)}>
Setting test2 className
</button>
</>
)
It is better not to use DOM querying and manipulation directly with elements that are created and controlled by react. In your particular example it is ok to use document.body, but not ok to search for buttons, especially when you try to find them by tag name. To actually toggle a class in classList you don't need second parameter in most cases, so additional state is also not needed.
React way to get reference to element renderend by React would be to use Ref. However, in your particular case side effect can be launched inside event handler, so you don't need useEffect or useRef.
Your onClick handler can accept event object that is Synthetic Event. It holds property target that holds reference to your button.
So, the easiest way would be simply to write like this:
function Test() {
function clickHandler(event) {
let classToToggle = event.target.getAttribute("custom-class");
document.body.classList.toggle(classToToggle);
}
return (
<>
<button key="test1" custom-class="test1" onClick={clickHandler}>
Setting test1 className
</button>
<button key="test2" custom-class="test2" onClick={clickHandler}>
Setting test2 className
</button>
</>
);
}
export default Test;
If you need to have only single className from the list, you can decide which class to enable or disable with a bit of a state. Since anything can add classes on body it might be useful to operate only on some set of classes and not remove everything.
Also, not mentioned before, but consider using data attribute as its purpose is to keep some additional data.
function Test() {
// this can come from props or be hardcoded depending on your requirements
// If you intend to change it in runtime, consider adding side effect to cleanup previous classes on body
let [classesList] = React.useState(["test1", "test2"]);
let [activeClass, setActiveClass] = React.useState("");
// You can switch actual classes in effect, if you want to
function clickHandler(event) {
let classToToggle = event.target.dataset.customClass;
// we remove all classes from body that are in our list
document.body.classList.remove(...classesList);
if (activeClass === classToToggle) {
setActiveClass("");
} else {
// if class not active - set new one
document.body.classList.add(classToToggle);
setActiveClass(classToToggle);
}
}
return (
<>
{classesList.map((cn) => (
<button key="cn" data-custom-class={cn} onClick={clickHandler}>
Setting {cn} className
</button>
))}
</>
);
}

Failing to pass onClick function to different file in React

So I have two .js files (are they also called modules?). The first .js file is a class-based component. It has handleClick() as well as render(). It looks like this (I've actually removed a lot of the code to make it appear shorter here):
handleClick(event) {
event.preventDefault()
console.log('handleclick')
this.initializeFetchApiAndSetState()
}
//Helper Function
checkGuessForCorrectAnswer() {
console.log('correct answer!')
}
render() {
return (
<div className="container-main">
<MultipleChoices
onClick={this.handleClick}
data={this.state.guess1}
/>
<button
className='Submit'
onClick={this.handleClick}
>
Submit
</button>
</div>
)
}
The button above works fine in that I can click on it and it'll console log the word 'correct answer!'. But for some reason, when I try to pass onClick to the "MultipleChoices" file/module it doesn't console log 'correct answer!'. The MultipleChoices.js file looks like this:
import React from "react"
function MultipleChoices(props) {
return(
<div>
<div className="button-grid">
<button
className="btn"
value={props.data}
onClick={props.handleClick}
>
{props.data}
</button>
</div>
</div>
)
}
export default MultipleChoices
Why can the button activate onClick in the first file, but not when I try to pass onClick to the MultipleChoice.js (which also has a button)?
In your upper component, you need to replace the onClick property with a handleClick property.
<MultipleChoices
handleClick={this.handleClick}
data={this.state.guess1}
/>
Because inside the Multiple Choices component you are calling the handleClick method from the properties (which is not set)
In your parent component you have given name to your property as onClick, while you are trying to acces it in children component as prop.handleClick.

React js - Show or hide a div

I am trying to show or hide a div in Reactjs using the state value in the CSS style option - display and I am using functions with hooks. I have a button and below the button a div. When i click the button i either want to hide or show the contents in the div based on whether it is currently shown or hidden.
This is the basic test code I have
import React, { useState } from "react";
function hide() {
return (
<div>
<Mycomp />
</div>
);
}
function Mycomp() {
const [dp, setDp] = useState("none");
return (
<form>
<button
onClick={() => {
setDp("block");
}}
>
Test
</button>
<div style={{ display: dp }}>Test</div>
</form>
);
}
export default hide;
I then use this hide component in my App.js file. When I click the button the new state is assigned but then the page re-renders and the initial state is loaded again almost immediately. How can I go by ensuring the new state is kept? Eventually I will create a function where if the div display or not based on the previous state.
The issue is that the button is inside a <form>. So any click on that button will submit the form and refresh the page.
Can I make a <button> not submit a form?
You need to add a type="button" to your <button>
import React, { useState } from "react";
function Hide() {
return (
<div>
<Mycomp />
</div>
);
}
function Mycomp() {
const [dp, setDp] = useState(false);
return (
<form>
<button
type="button"
onClick={() => setDp(!dp)}
>
Test
</button>
{dp && <div>Test</div>}
</form>
);
}
export default Hide;
Your code should be something like this, instead of using block and none as style we can use conditional JSX (which is more ideal approach) -:
function Mycomp(){
const[dp, toggleDp] = useState(false);
return(
<form>
<button onClick={()=>{toggleDp(!dp)}}>Test</button>
{dp && <div>Test</div>}
</form>
)
}
export default hide
A better implementation would be to have your state variable TRUE/FALSE value and based on it display the element using a conditional rendering, note e.preventDefault in the button handler to stop the refresh/redirect, here is a working snippet, also a codesandbox:
const { useState, useEffect } = React;
function App() {
return (
<div>
<Mycomp />
</div>
);
}
function Mycomp() {
const [dp, setDp] = useState(true);
return (
<form>
<button
onClick={(e) => {
e.preventDefault();
setDp(!dp);
}}
>
Test
</button>
{dp && <div>Test</div>}
</form>
);
}
ReactDOM.render(<App />, document.getElementById("react-root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

Next.js toggle display of a div tag

Code
export default function Header(){
let showMe = false;
function toggle(){
showMe = !showMe;
}
return (
<>
<button onClick={toggle}>Toggle Subjects</button>
{/*The bottom code should toggle on and off when the button is pressed*/}
<div style={{
display: showMe?"block":"none"
}}>
This should toggle my display
</div>
</>
);
}
Expectation
The div tag should toggle in visibility (For example, if I clicked on the button once, the div tag should show up, and if I clicked on it again it would be hidden and so on).
Reality
It appears the variable showMe changes however the div tag does not follow with the updates and remains hidden.
NOTE: I am using next.js if that changes anything.
showMe needs to be a state variable so that React knows to rerender the component when showMe changes. I'd read this: https://reactjs.org/docs/hooks-state.html
The code below should work (note how showMe is replaced with a call to useState).
export default function Header(){
const [showMe, setShowMe] = useState(false);
function toggle(){
setShowMe(!showMe);
}
return (
<>
<button onClick={toggle}>Toggle Subjects</button>
{/*The bottom code should toggle on and off when the button is pressed*/}
<div style={{
display: showMe?"block":"none"
}}>
This should toggle my display
</div>
</>
);
}
The bracket notation const [showMe, setShowMe] = useState(false); is Array Destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
useState returns an array of length 2. Using array destructuring, we set the first element of the returned array to showMe and the second element of the returned array to setShowMe.

Categories