react - add a classname to a specific element by clicking the button - css

I am new to reactjs. A sign in and sign up component is created. When clicking the button, a classname is supposed to be added to the specific element, in my case, signWrapper. I've tried few ways but it doesn't work. How do I add a classname to a specific element by clicking the button?
My code is on the codesandbox. Any suggestions are highly appreciated.
https://codesandbox.io/s/stoic-hertz-pmk23?file=/src/SignInAndSignUp.js:0-2298

you used your onClick function in a wrong way . you have to invoke this .
instead of this
onClick = { () => this.handleClick}
you have to do this
onClick = { () => this.handleClick()}
and handle your onClick like this
handleClick = () => {
this.setState({ active: !this.state.active }); // to toggle the state
};
here is the working example https://codesandbox.io/s/delicate-star-ghp7h?file=/src/SignInAndSignUp.js:283-360

Invoke your onClick function like so:
onClick={this.handleClick}
handleClick = () => {
// I added ...this.state so it doesn't affect any other state variables you may add
this.setState({ ...this.state, active: !this.state.active });
};
Also, check out the library clsx. It's very helpful when you have multiple classes needing to be activated or unactivated based on conditionals. This would look something more like the following:
className={clsx('signWrapper', { 'right-panel-active': active })}

Related

How to select all of the elements with class "backbtn" that is in another function?

I am trying to select all the elements with the class "backbtn", but its not that easy since all the elements with that class is currently not in the DOM when page is freshly loaded but only in the DOM when a certain button is clicked.
I tried fixing it by putting it in a setInterval like this:
document.querySelector(".backbtn").forEach(el => el.addEventListener("click", () => {
if(document.querySelector(".backbtn")!=null){
goBack();
} return null;
}))
}, 10)```
but it dosent work.

Creating on/off button in react

I am making a button that is going to say "disable" when its on and "enable" when its off. how do I do that in react?? I have tried to make it but I have no idea where to even start, is there some syntax im missing?
The code below does the job of displaying the button text based on a state.
Inside the useState() hook you can specify the initial state.
On the button's click event the state will be reversed to toggle between true and false
const customButton = () => {
const [enabled, setEnabled] = useState(false);
return (
<button
onClick={() => setEnabled(!enabled)}>
{enabled ? "disable" : "enable"}
</button>
);
}

Why Material UI buttons not working correctly on onClick events? [duplicate]

I am trying to add an onClick eventhandler into a material ui and sometimes it is called, sometimes it is not. However, it's working fine with regular buttons
handleClick = (event) => {
const value = event.target.value;
console.log(value);
this.setState({ filtered: this.state.videos.filter(item => {
return item.category === value
})
})
<Button value="java" onClick={this.handleClick} color="primary">Java</Button>
<Button value="React" onClick={this.handleClick} color="primary">React</Button>
<Button value="C#" onClick={this.handleClick} color="primary">C#</Button>
<Button value="javascript" onClick={this.handleClick} color="primary">JavaScript</Button>
when I updated to console.log to get event.target, I got the result shown in the image below
I found the issue, but still don't know how yo fix it. React adds two spans to the Button that have no attribute name, so when I click the button, the function gets called, but not when I click the span
You can use event.currentTarget.value instead of event.target.value.
Material-ui's Button has a nested span inside the button, so when you use event.target.value and the user clicks the span you get the span as event.target, if you'd use event.currentTarget you'd get the element that the event listener is attached to - the button.
See a working example: https://codesandbox.io/s/cocky-cookies-s5moo?file=/src/App.js
Inside your handle click, you could also do:
return (item.category === value || item.category === event.target.innerHTML)
But obviously CD..’s answer is better
Besides relying on currentTarget, you can always curry the parameter to the callback function (imagine you are not passing in static content, but maybe the index of an iteration or some dynamic values stored in an object, etc)
Example
handleClick = (value) => () => {
console.log(value);
this.setState({ filtered: this.state.videos.filter(item => {
return item.category === value
})
})
<Button value="java" onClick={this.handleClick('java')} color="primary">Java</Button>
<Button value="React" onClick={this.handleClick('React')} color="primary">React</Button>
<Button value="C#" onClick={this.handleClick('C#')} color="primary">C#</Button>
<Button value="javascript" onClick={this.handleClick('javascript')} color="primary">JavaScript</Button>

React: Stop click event propagation when using mixed React and DOM events

We have a menu. If menu is open, We should be able to close it by clicking anywhere:
class Menu extends Component {
componentWillMount() {
document.addEventListener("click", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleClickOutside);
}
openModal = () => {
this.props.showModal();
};
handleClickOutside = ({ target }) => {
const { displayMenu, toggleMenu, displayModal } = this.props;
if (displayMenu) {
if (displayModal || this.node.contains(target)) {
return;
}
toggleMenu();
}
};
render() {
return (
<section ref={node => (this.node = node)}>
<p>
<button onClick={this.openModal}>open modal</button>
</p>
<p>
<button onClick={this.openModal}>open modal</button>
</p>
<p>
<button onClick={this.openModal}>open modal</button>
</p>
</section>
);
}
}
From menu, we can open a modal by clicking on button inside menu. We can close modal in two ways: by clicking close modal button inside modal, or on click on bakcdrop/overlay outside the modal:
class Modal extends Component {
hideModal = () => {
this.props.hideModal();
};
onOverlayClick = ({ target, currentTarget }) => {
if (target === currentTarget) {
this.hideModal();
}
};
render() {
return (
<div className="modal-container" onClick={this.onOverlayClick}>
<div className="modal">
<button onClick={this.hideModal}>close modal</button>
</div>
</div>
);
}
}
And now, when menu and modal is open, on close modal click or modal overlay click I want to close only modal, menu should be still open. Only on second click (while modal is closed). At first glance it look pretty clear and easy, this condition should be responsible for that:
if (displayModal || this.node.contains(target)) {
return;
}
If displayModal is true, nothing should happen. I'ts do not work, cause in my case, when you click at the close modal button or overlay, hideModal will be done faster than toggleMenu, and when we call handleClickOutside displayModal will already have false.
Full test case with open menu and modal at the start:
https://codesandbox.io/s/reactredux-rkso6
This is gonna be a bit longer, as I have investigated in similar issue recently. If you don't want to read everything, just have a look at the solutions.
Solutions
Two solutions come to my mind - the first is the easy fix, the second is cleaner, but requires an additional click handler component.
1.) Easy fix
In Modal.js onOverlayClick, add stopImmediatePropagation like this:
onOverlayClick = e => {
// this is to stop click propagation in the react event system
e.stopPropagation();
// this is to stop click propagation to the native document click
// listener in Menu.js
e.nativeEvent.stopImmediatePropagation();
if (e.target === e.currentTarget) {
this.hideModal();
}
};
On document, there are two click listener registered: a) the first is the top level listener of React b) your click listener in Menu.js. With e.nativeEvent you get the native DOM event wrapped by React. stopImmediatePropagation will cancel the second listener - and prevents closing of the menu, when you just want to close the modal. You can read more under explanation.
Codesandbox
2.) The clean one
With this solution, you can just use event.stopPropagation. All event handling (incl. the outside click handler) is done by React, so you don't have to use document.addEventListener("click",...) anymore. The click-handler.js down under will be just some proxy that catches all click events at the top level and forwards them in the React event system to your registered components.
Create click-handler.jsx:
import React from "react";
export const clickListenerApi = { addClickListener, removeClickListener };
export const ClickHandler = ({ children }) => {
return (
<div
// span click handler over the whole viewport to catch all clicks
style={{ minHeight: "100vh" }}
onClick={e => {
clickListeners.forEach(cb => cb(e));
}}
>
{children}
</div>
);
};
// state of registered click listeners
let clickListeners = [];
function addClickListener(cb) {
clickListeners.push(cb);
}
function removeClickListener(cb) {
clickListeners = clickListeners.filter(l => l !== cb);
}
Menu.js:
class Menu extends Component {
componentDidMount() {
clickListenerApi.addClickListener(this.handleClickOutside);
}
componentWillUnmount() {
clickListenerApi.removeClickListener(this.handleClickOutside);
}
openModal = e => {
// This click shall not close the menu,
// so don't propagate the event to our clickListener API.
e.stopPropagation();
const { showModal } = this.props;
showModal();
};
render() {... }
}
index.js:
const App = () => (
<Provider store={store}>
<ClickHandler>
<Page />
</ClickHandler>
</Provider>
);
Codesandbox
Explanation:
When you have both modal dialog and menu open and click once outside the modal, then with your current code the behavior is correct - both elements are closed. That is because in the DOM document has already received the click event and prepares itself to invoke your handleClickOutside click handler in Menu. So you have no chance anymore to cancel it via e.stopPropagation() in onOverlayClick callback of Modal.
In order to understand the order of both firing click events, we have to comprehend that React has its own synthetic Event Handling system (1, 2). The main point here is that React uses top level event delegation and adds one single listener to document in the DOM for all event types.
Let's say you have a button <button id="foo" onClick={...}>Click it</button> somewhere in the DOM. When you click the button, it triggers a regular click event in the browser, that bubbles up to document and further until it reaches DOM root. React catches this click event with its single listener at document, and then internally traverses its virtual DOM again (similar to capture and bubble phase of the native DOM) and collects all relevant click callbacks that you have set with onClick={...} in your components. So your button onClick will be found and invoked later on.
Here is the interesting part: by the time React deals with the click events (which are now synthetic React events), the native click event had already gone through the full capture/bubbling cycle in the DOM and doesn't exist in the native DOM anymore! That is the reason, why a mix of native click handlers (document.addEventListener) and React onEvent attributes in the components' JSX sometimes is so hard to handle and unpredictable. React event handlers should always be preferred.
Links to read on:
Understanding React's Synthetic Event System (also the linked article with it)
ReactJS SyntheticEvent stopPropagation() only works with React events?
https://fortes.com/2018/react-and-dom-events/
Hope, it helps.
Call event.stopPropagation() inside your onOverlayClick() method and hideModal(), this will prevent the event to bubble up to the parent. Like this.
onOverlayClick = e => {
e.stopPropagation();
if (e.target === e.currentTarget) {
this.hideModal();
}
};
Just add a little timeout to let the displayMenu variable updates:
class Modal extends Component {
hideModal = () => {
const { hideModal } = this.props;
setTimeout(() => {
hideModal();
}, 200); // Could work with 100ms
};
...
Working example

Hiding Submit Button with offline.js

I am using offline.js (0.7.18) and its working fine, when I go on/offline the indicator changes state, all good so far.
I can also see on Offline JS Simulate UI, that a login panel is having its style toggled between display:block and display:none when on/offline is triggered. But I can't discover how this works.
I want to hide a 'Submit' button when offline is triggered.
You can use the sample from the Offline JS Simulate UI page that uses jQuery:
<script>
$(function(){
var
$online = $('.online'),
$offline = $('.offline');
Offline.on('confirmed-down', function () {
$online.fadeOut(function () {
$offline.fadeIn();
});
});
Offline.on('confirmed-up', function () {
$offline.fadeOut(function () {
$online.fadeIn();
});
});
});
</script>
Give the class "online" to any element you want shown when the system is online and give the class "offline" to any element you want shown when the system is offline.
<button class="online">ABC</button>

Resources