React Global Memoization - reactjs

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".

Related

Apply CSS transition to styled-component when React state changes

I have some state that changes after button click. The state changes the size of a sidebar.
Here is my CSS made with styled-components and conditional rendering:
const SidebarStyled = styled.div`
width: ${this.state.sidebarOpen ? '200px' : '70px'};
position: fixed;
left: 0px;
top: 0px;
height: 100vh;
background-color: #0c1635;
display: flex;
flex-direction: column;
`;
Any idea how I can apply a transition 0.2s on the conditional rendering?
I have tried to add transition: all 0.2s ease-in-out; and it didn't work.
As I mentioned in my comment, you need to pass in a prop and interpolate it out to change your CSS. Otherwise your component will re-render, and the CSS transition won't be applied.
const { React, ReactDOM, styled } = window;
class WontWork extends React.Component {
constructor(props) {
super(props);
this.state = { sidebarOpen: false };
}
render() {
const Sidebar = styled.div`
width: ${this.state.sidebarOpen ? "200px" : "70px"};
height: 20px;
background: red;
transition: width 1s;
`;
return (
<main>
<p>This won't work:</p>
<Sidebar />
<button
onClick={() => this.setState({ sidebarOpen: !this.state.sidebarOpen })}
>
Expand
</button>
</main>
);
}
}
const WorkingSidebar = styled.div`
width: ${(props) => (props.open ? "200px" : "70px")};
height: 20px;
background: green;
transition: width 1s;
`;
class WillWork extends React.Component {
constructor(props) {
super(props);
this.state = { sidebarOpen: false };
}
render() {
return (
<main>
<p>You need to pass in a <b>prop</b> to a predefined styled-component:</p>
<WorkingSidebar open={this.state.sidebarOpen} />
<button
onClick={() => this.setState({ sidebarOpen: !this.state.sidebarOpen })}
>
Expand
</button>
</main>
);
}
}
ReactDOM.render(
<div>
<WontWork />
<hr />
<WillWork />
</div>,
document.getElementById("app")
);
<script crossorigin src="https://unpkg.com/react#16.14.0/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16.14.0/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/react-is#16.13.1/umd/react-is.production.min.js"></script>
<script crossorigin src="https://unpkg.com/styled-components#5.3.3/dist/styled-components.min.js"></script>
<div id="app"></div>
Try this:
You can passe sidebarOpen as props:
<SidebarStyle sidebarOpen = {this.state.sidebarOpen}>
Then:
const sidebarStyle = styled.div`
width: 70px;
transition: transform .2s ease-in-out;
transform: ${props.sidebarOpen ? "scaleX(3)" : "scaleX(1)"};
.
.
.
`
I helped from here:
See here: Adding transitions to styled components
Does it work In this case?
Add a transition property like: transition:all 200ms ease-in;

Conditional rendering + React

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;

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.

What is the most efficient way to toggle between two components React JS? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have seen multiple examples on how to toggle a single component's visibility but what would be the most efficient way to toggle between the visibility of two sibling components in React?
I typically use a separate function with some logic to decide what to display, and place that function within the main render function. Take the code below for example:
const FirstComponent = (props) => {
return (
<div className='first-class'>Hello, I am the first component!</div>
)
}
const SecondComponent = (props) => {
return (
<div className='second-class'>And I am the second component!</div>
)
}
class MainComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: 'first'
};
}
changeDisplay = () => {
let { display } = this.state;
this.setState({ display: display === 'first' ? 'second' : 'first' });
}
renderInner() {
let { display } = this.state;
if (display === 'first') {
return <FirstComponent />
} else if (display === 'second') {
return <SecondComponent />
}
}
render() {
return (
<div className='main-class'>
<div className='button' onClick={this.changeDisplay}>Click me</div>
{this.renderInner()}
</div>
);
}
}
const root = document.getElementById('app');
ReactDOM.render(<MainComponent />, root);
.first-class {
background: blue;
display: inline-block;
}
.second-class {
background: red;
display: inline-block;
}
.main-class {
margin-top: 10px
width: 400px;
height: 100px;
background: #eee;
}
.button {
padding: 5px 12px;
border: 1px solid #ccc;
background: #ddd;
border-radius: 3px;
display: inline-block;
margin: 5px;
cursor: pointer;
user-select: none;
}
.button:hover {
background: #ccc;
border-color: #bbb;
}
<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='app'></div>
{toggle?<Component1 /> : <Component2 />}
Seems to be the most readable approach. This is common to see this to display a fake component while loading a component:
{loaded?<Component /> : <Loading />}
I haven't touched the library in a while, but I'm pretty sure the best way is:
Obviously have a parent component of both
Each child component should have shouldComponentUpdate() implemented in such a way that a re-render will only trigger when it actual require an update.
This way, you can switch both of them without worrying about unnecessary renders

setState not updating font awesome icon

I'm trying to dynamically render font awesome icon in myself written checkbox component. When I'm trying to update state of a with font awesome icon after clicking on it it is not updating. I've tried to move render to separate function and tried to use react-fontawesome but nothing helps. The state is updating but font awesome icons are the same svg code in html.
...
state = {
checked: this.props.checked
}
toggleCheck = () => {
this.setState({ checked: !this.state.checked });
};
render () {
const iconUnchecked = 'far fa-square';
const iconChecked = 'fas fa-check-square';
const iconClass = this.state.checked ? iconChecked : iconUnchecked;
return (
<span onClick={this.toggleCheck}>
<i className={iconClass} />
</span>
);
}
As I understood the font awesome js manipulates DOM and React manipulates virtual DOM. When font awesome js doing its own stuff React can't rerender it after state change. Im still on React 15 and maybe it's not the issue in React 16. I just found a solution for me to put every with font awesome in a div with unique key. This way React see that div must change because key was changed.
Try that one https://jsfiddle.net/n5u2wwjg/30533/
For me seems to work
Check exactly jsfiddle it works, but not a snippet. Snippet is just to satisfy editor.
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: this.props.checked
}
this.toggleCheck = this.toggleCheck.bind(this);
}
toggleCheck() {
this.setState({ checked: !this.state.checked });
}
render() {
const iconUnchecked = 'far fa-square';
const iconChecked = 'fas fa-check-square';
let iconClass = this.state.checked ? iconChecked : iconUnchecked;
return (
<span onClick={this.toggleCheck}>
<i className={iconClass} />
</span>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">
<div id="app"></div>
I too faced the same trouble. As 200Ok mentioned it correctly, svg--inline-fa is not a virtual DOM so it never gets updated. The best way to solve the problem is to wrap the font awesome elements that would contain the decisive classes.

Resources