Conditional rendering + React - reactjs

i tried making a method that holds the previous state, and changes back to the the previous state on click. Yet I checked if the method was working, and it was properly changing between true and false.
Yet, when I do a ternary operator in the className, it stays as the true value, and does not let me toggle between two classes. The first being the regular border, and the second having the position absolute with the checkmark to indicate it was selected. Even when I check dev tools, 'checkmark' is the className but nothing changes onClick...
import React from 'react';
import './Questions.css'
import girl_sweat from './girl_sweat.jpg'
class Questions extends React.Component {
constructor(props){
super(props);
this.state = {
isChoiceClicked: false
}
this.handleChoice = this.handleChoice.bind(this);
}
handleChoice(){
this.setState(prevState => ({isChoiceClicked: !prevState.isChoiceClicked}));
}
render(){
const isChoiceClicked = this.state;
return <div className="banner_column">
<div className="banner_column_1"><img src={girl_sweat}/></div>
<div className="banner_column_2"><div className="survey_enter"><h2 className="title">What are you interested in?</h2>
<p className="description">Select up to <strong>3 areas</strong></p>
<div className="choices">
<div className={`choice_container ${isChoiceClicked ? 'checkmark': 'null'}`} onChange={this.handleChoice}><h5>Yoga</h5><p className="activities">Vinyasa, Ashtanga, Kundalini, Hatha, Restorative, Prenatal</p></div>
<div className={`choice_container ${isChoiceClicked ? 'checkmark': 'choice_container'}`} onChange={this.handleChoice}><h5>Fitness</h5><p className="activities">Strength, Barre, Pilates, HIIT, Core, Stretching</p></div>
<div className={`choice_container ${isChoiceClicked ? 'checkmark': 'choice_container'}`} onChange={this.handleChoice}><h5>Mindfullness</h5><p className="activities">Meditation, Breathwork, Sound Bath, Yoga Nidra</p></div>
<div className={`choice_container ${isChoiceClicked ? 'checkmark': 'choice_container'}`} onChange={this.handleChoice}><h5>Skills</h5><p className="activities">Handstands, Arm Balances, Flexibility, Mobility</p></div>
</div>
<div className="next"><button className="next_question">next question</button></div>
</div>
</div>
</div>
}
}
export default Questions; ```
.choice_container {
margin: 0 auto;
width: 250px;
padding: 1rem;
border: solid 0.5px black;
position: relative;
}
.choice_container .checkmark {
display: hidden;
position: absolute;
border: solid 2px black;
right: -8px;
top: -8px;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #000;
color: #fff;
content: "✓";
}```

Even when I check dev tools, 'checkmark' is the className but nothing changes onClick
The function you activate should be onClick rather than onChange.
Usually onChange can be used in <input> and <select>. However, if you are using div, using onChange seems to be a problem.
<div className={`choice_container ${isChoiceClicked ? 'checkmark': 'null'}`} onClick={this.handleChoice}><h5>Yoga</h5><p className="activities">Vinyasa, Ashtanga, Kundalini, Hatha, Restorative, Prenatal</p></div>
Besides, I guess you wanna destructure from this.state. Therefore, you can do the following thing.
const isChoiceClicked = this.state;
const { isChoiceClicked } = this.state;

Related

React body scroll lock issue on IOS

I'm literally fighting in finding a clean solution to the scroll issue in the IOS devices. In my App.js i've simply the background body and a modal with some contents. When the modal is shown i'd like to block the scroll in the background (myBodyContent) and still let the scroll in the modal component. I'm quite new to both javascript and React and this not helping me at all.
The cleanest solution (according to me) i was able to find is the body-scroll-lock package but it seems i'm not able to successfully use it. here is my code:
App.js
class App extends Component {
targetRef = React.createRef();
targetElement = null;
constructor(props) {
super(props);
}
componentDidMount() {
this.targetElement = this.targetRef.current;
disableBodyScroll(this.targetElement);
}
render() {
const myModal = (
<Modal ref={this.targetRef}>
// my long content here
</Modal>);
return (
<React.Fragment>
{myModal}
<Layout>
<myBodyContent>
</Layout>
</React.Fragment>
);
}
}
Modal.js
class Modal extends Component {
shouldComponentUpdate(nextProps, nextState){
return (nextProps.show !== this.props.show)
}
render () {
return (
<div>
<Auxi>
<Backdrop
show = {this.props.show}
clicked = {this.props.modalClosed}
/>
<div className={style.Modal}
style={{
transform: this.props.show ? 'translateY(0)' : 'translateY(-100vh)', // vh is special unit for outside screen
opacity: this.props.show ? '1': '0'
}}>
{this.props.children}
</div>
</Auxi>
</div>
);
}
}
Modal css
.Modal {
position: fixed;
z-index: 500;
background-color: white;
width: 80%;
overflow-y: hidden;
overflow: auto;
padding-right: 15px; /* Avoid width reflow */
border: 1px solid #ccc;
box-shadow: 1px 1px 1px black;
padding: 16px;
top: 5%;
left: 5%;
box-sizing: content-box;
transition: all 0.3s ease-out;
}
#media (min-width: 600px) {
.Modal {
width: 80%;
height: 80%;
left: 10%;
top: 10%
}
}
With the above code, simply everything is locked and i cannot scroll neither the modal nor the myBodyContent.
Can you help me understanding what i'm doing wrong? Or suggest me some other ways to achieve the same result?
Thanks in advance for your help.
You don't have targetElement (it's null) inside App componentDidMount because you try to set ref for React component but not HTML element.
To fix this you need to forward ref inside Modal component like that:
const myModal = (
<Modal forwardedRef={this.targetRef}>
// my long content here
</Modal>
);
and then :
class Modal extends Component {
shouldComponentUpdate(nextProps, nextState){
return (nextProps.show !== this.props.show)
}
render () {
return (
<div ref={this.props.forwardedRef}>
<Auxi>
<Backdrop
show = {this.props.show}
clicked = {this.props.modalClosed}
/>
<div className={style.Modal}
style={{
transform: this.props.show ? 'translateY(0)' : 'translateY(-100vh)', // vh is special unit for outside screen
opacity: this.props.show ? '1': '0'
}}>
{this.props.children}
</div>
</Auxi>
</div>
);
}
}
Thanks Max, i've tried but unfortunately the result is the same. I've also tried to enclose the Modal in a div directly in the App.js and apply the ref directly there without passing it as props...but it's the same. No way to scroll anything.

React Global Memoization

I have the following React test app:
class MemoTestApp extends React.Component {
constructor(props) {
super(props)
this.state = {
showOverlay: false,
}
}
render() {
return (
<div>
<div>
<MemoComponent str="Hello World" />
</div>
<div>
<input type="button" onClick={() => this.setState({showOverlay: true})} value="Show Overlay"/>
</div>
{this.state.showOverlay && (
<div className="overlay">
<h2>Overlay</h2>
<MemoComponent str="Hello World" />
</div>
)}
</div>
)
}
}
const Component = (props) => {
console.info('render ' + props.str);
return <div>{props.str}</div>;
}
const MemoComponent = React.memo(Component);
ReactDOM.render(<MemoTestApp />, document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
position: relative;
min-height: 200px;
}
.overlay {
position: absolute;
padding: 20px;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
As you can see, there is a memoized functional component which is rendered twice with the same props. The first rendering takes place immediately, the second one after the user presses the button.
However, the component really is rendered twice, as you can see in the console. React.memo prevents the second rendering of the first instance of the component, but the second instance seems to "now know" that this component has already been rendered with the given props.
Is there a way to make Memoization "global", i.e. so that rendered outputs are shared between different instances of the component?
What is the reason that React.memo is not global by default?
Short answer: Components are reusable, this is by design.
They may have their own state, for example a counter. Or they have side effects, e.g. own intervals, custom logic depending on the DOM nodes.
For that reason, they have to be separate "instances" depending where they live on the DOM (parent node, index or key), and are separately rendered. The result is then memoized per component "instance".

How to show Vertical Progress Bar in react-transition-group with animation

Here is a jQuery example for a progress bar animation. and I want this feature in Reactjs without jQuery. How to implement this feature.
I hope you are still interested in this question. I just tinker with react-spring and I really love it. The best animation library in React IMHO.
You can create a neat component with the Spring component. It will always animate to the to property of the Spring component. First time from the from value of the from property.
import React from "react";
import { Spring } from "react-spring";
const VerticalProgress = ({ progress }) => {
return (
<Spring from={{ percent: 0 }} to={{ percent: progress }}>
{({ percent }) => (
<div className="progress vertical">
<div style={{ height: `${percent}%` }} className="progress-bar">
<span className="sr-only">{`${progress}%`}</span>
</div>
</div>
)}
</Spring>
);
};
export default VerticalProgress;
Here is the complete code: https://codesandbox.io/s/mqo1r9wo4j
Horizontal Example
Here is how to do it.
make 2 divs(container, progressing one)
you can change the height of progressing div based on state change.
const styled = styled.default;
const Bar = styled.div`
position: relative;
height: 500px;
width: 100%;
border-radius: 3px;
border: 1px solid #ccc;
margin: 1rem auto;
`
const Fill = styled.div`
background: #0095da;
width: 100%;
border-radius: inherit;
transition: height 0.2s ease-in;
height: ${(props) => `${props.percentual}%`};
`
const ProgressBar = ({ percentage }) => {
return (
<div>
<Bar>
<Fill percentage={percentage} />
</Bar>
</div>
);
}
ReactDOM.render(<ProgressBar percentage={you state for progress percentage} />, document.getElementById('bar'));
you don't even need react for that tho.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_progressbar_label_js

In ReactJs is it possible/feasible to perform rendering during a Drag/Drop operation?

In ReactJs is it possible/feasible to perform rendering during a Drag/Drop operation?
The specific use case I had in mind was trying to build a month view calendar in ReactJS that, during dragging of a multi-day event backwards and forward, all the other day events on the calendar would move backwards forward to show (whist the use is still dragging) what the effect would be on all events before the do actually "drop" it. (i.e. assumes only one event on any given day, so page would aim to move/swap day events around when user is moving one)
Similar to drag dropping a movie clip on a movie timeline, and you see how the clips would swap around during the drag, highlighting what would happen if the user did release the mouse button and do the "drop".
Question: Is is this possible/recommend in ReactJS? If yes, what would be the concept here? i.e. what call would one be making to trigger a "refresh" during the drag event handler? Or if in the drag event handler you just reposition other components/events does React just render on-the-fly during the drag automatically?
Yes - with an example below:
import React, { Component } from 'react';
import 'rc-slider/assets/index.css';
import './GcSlider.css';
export class GcSlider extends Component {
state = {
value: 50,
};
handleChange = (value) => {
this.setState({ value });
};
buttonClick = (e) => {
console.log('Button Clicked');
}
render() {
const { value } = this.state;
let divs = [1,2,3,4,5,6,7,8,9].map(item => <div className="box {item}">Item {item}</div>)
console.log('DIVS = ' + divs)
return (
<div>
<div style={{alignContent:true}}>
<h1>Hello</h1>
</div>
<div className="wrapper">
{ divs }
<div className="box {item}"></div>
<div className="box {item}">Item B</div>
<div className="box {item}">Item C</div>
<div class="overlay" draggable>oevrlay</div>
</div>
</div>
)
}
}
export default GcSlider
and css
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
.box {
border-radius: 5px;
border: 1px solid brown;
font-size: 150%;
height: 120px;
}
.overlay {
position: absolute;
top: 0px;
height:80px;
border: 2px solid red;
}

react Semantic-UI - multi-select checkbox drop-down

i want to built an multi select checkbox dropdown in react with es6
my requirement is as below specified in image
I tried doing this click here but it is not working.
You can use one parent component that will keep values in its state and toggle list items. Then you can create component for each list item that will keep active property in state that you can toggle on click.
class ListItem extends React.Component {
constructor(props) {
super(props);
this.state = {active: false}
}
render() {
return (
<a
onClick={() => {
this.setState(prevState => {
let newState = !prevState.active;
this.props.handleClick(newState, this.props.value);
return {active: newState}
})
}}
className={!this.state.active ? '' : 'selected'}
href="#">
{this.props.value}</a>
)
}
}
class Select extends React.Component {
constructor(props) {
super(props);
this.state = {
showList: false,
value: []
}
this.handleItemClick = this.handleItemClick.bind(this)
}
componentDidMount() {
document.addEventListener('mousedown', (e) => {
if(!this.node.contains(e.target)) {
this.setState({showList: false})
}
})
}
componentWillUnmount() {
document.removeEventListener('mousedown');
}
renderValue() {
let {value} = this.state;
if(!value.length) return "Select..."
else return value.join(', ')
}
toggleList() {
this.setState(prevState => ({showList: !prevState.showList}))
}
handleItemClick(active, val) {
let {value} = this.state;
if(active) value = [...value, val]
else value = value.filter(e => e != val);
this.setState({value})
}
render() {
return (
<div
ref={node => this.node = node}
className="select">
<button onClick={this.toggleList.bind(this)}>
<span className="select_value">
{this.renderValue()}
</span>
</button>
<div
className={"select_list " + (!this.state.showList && 'hide')}>
<ListItem handleClick={this.handleItemClick} value="Lorem" />
<ListItem handleClick={this.handleItemClick} value="Ipsum" />
<ListItem handleClick={this.handleItemClick} value="Dolor" />
</div>
</div>
)
}
}
ReactDOM.render(
<Select />,
document.getElementById('container')
);
button {
background: white;
width: 100%;
padding: 10px 15px;
border: 1px solid rgba(0, 0, 0, .1);
border-radius: 5px;
cursor: pointer;
text-align: left;
}
.select_list {
width: 100%;
background: white;
border: 1px solid rgba(0, 0, 0, .1);
border-radius: 5px;
}
.select_list a {
padding: 10px 15px;
display: flex;
color: black;
text-decoration: none;
position: relative;
align-items: center;
}
.select_list a:before {
width: 15px;
height: 15px;
content: '';
border: 1px solid rgba(0, 0, 0, .1);
border-radius: 5px;
margin-right: 10px;
display: block;
}
.select_list a.selected:before {
background: #0493D1;
content: '✓';
color: white;
font-size: 11px;
text-align: center;
line-height: 15px;
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
Semantic-UI React Approach
After much digging, I found an old conversation between eugenetumachov and Semantic-UI developers(?). One of the users provided incredibly helpful code that answers this question using Semantic-UI's Dropdown component.
This is done by making use of Dropdown's Dropdown.Menu and Dropdown.Item. Then looping through your options via map to create checkboxes. The only downside is that the workaround does not seem to allow scrolling and will require more CSS. Additionally, based on CSS the checkbox items' background color may turn transparent if you double-click on the dropdown, and the dropdown will collapse on mouse hover. You can bypass the transparency issue by using a class or style property for your Dropdown.Menu and Dropdown.Item.
Semantic-UI developer's response to this type of question appears to be a flat "no" or a
Active items are automatically removed from the Dropdown menu. So you cannot show a "checked" state for an item in the menu.
You could create a similar component out of an Input as a trigger for
a Popup containing a Menu or List of Checkboxes.
Are dropdowns with checkboxes possible? #2417
eugenetumachov's workaround

Resources