ReactJs, Losing child component local state on global state change - javascript

I'm not understanding some ReactJs behavior and would need some help.
I have a Root Functional Component ("Index"), that contains another functional Component ("Preview").
That Preview component contains several other Functional Components ("InlineField").
The app is a simple form, where InlineField is component that renders an input and also contains a state to know if the field is "opened" or "closed" (when close it is displayed as a text, when open it is displayed as an input).
The global state is defined using hooks ad the "Index" level and moved down to the field through props (I've tried the same using Context). This state contains all form values.
The InlineField Component uses hook to maintain its local state only (is open / is closed).
When a an input is changed it updates the state (Index level) which triggers a re-render of the Index as well as its children.
This translate into the currently edited field (InlineField Component with local state = open) to refresh and lose its state value.
My question:
How can I make sure these InlineField Components retain their state even after updating global state?
I could simply move that InlineField Component state to the global state too, but I don't think it makes much sense.
I must be getting something wrong...
Thanks!
Edit: added code sample
Index Component:
import React, { useState, useEffect } from "react"
import Layout from "../components/layout"
const IndexPage = () => {
const [formValues, setFormValues] = useState({
name: 'Myname',
email: 'myemail#mail.com',
})
const onFormValueChange = (key, value) => {
setFormValues({...formValues, [key]: value})
}
return (
<Layout>
<Preview
key="previewyaknow"
formValues={formValues}
onFieldChange={setFormValues}
/>
</Layout>
)
}
export default IndexPage
Preview Component:
import React from 'react'
import { Box, TextField } from "#material-ui/core"
import { InlineField } from './inlineField'
export const Preview = ({formValues, onFieldChange}) => {
return (
<>
<Box display="flex" alignItems="center">
<InlineField
value={formValues.email}
onChange={onFormValueChange}
id="email"
field={<TextField value={formValues.email}/>>>}
/>
</>
)
}
InlineEdit Component
import React, { useState, useEffect } from "react"
export const InlineField = ({onChange, value, id, field}) => {
const [isEdit, setIsEdit] = useState(false)
const onBlur = (e) => {
setIsEdit(false)
}
let view = (<div>{value}</div>);
if (isEdit) {
view = (
<FieldContainer className={classes.fieldContainer}>
{React.cloneElement(field, {
'onBlur': onBlur,
'autoFocus': true,
'onChange': (e) => {
onChange(id, e.target.value)
}
})
}
</FieldContainer>
)
}
return (
<div onClick={()=>setIsEdit(!isEdit)}>
{view}
</div>
)
}

Related

why role base parent of two child component have different state if update in one of these child component in reactjs

I want to know I have one parent component and two child components and these child components are separated according to the user role. I have passed the parent state in these child components. In the beginning, both child components have the same state value, but if I update the state value in one child component, it will not update the state value in another component why.
Here is an example code.
import React, { useEffect, useState } from "react";
import Demo1 from "./Demo1";
import Demo2 from "./Demo2";
const Demo = () => {
const [staVal, setStaVal] = useState("hi");
console.log(staVal);
const user = JSON.parse(localStorage.getItem("auth"));
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};
export default Demo;
Demo1 component:
import React from "react";
const Demo1 = ({ staVal, setStaVal, handler }) => {
return (
<>
<div>demo1:{staVal}</div>
<button onClick={handler}>clik</button>
</>
);
};
export default Demo1;
Demo 2 component:
import React from "react";
const Demo2 = ({ staVal }) => {
return <div>demo2:{staVal}</div>;
};
export default Demo2;
Accessing localStorage is a side effect.
Side effects cannot be called from the render method (for Class components) or the top level (function components).
In your code, access the localStorage inside useEffect(()=>{}, []) or
inside componentDidMount if you want to make it a class component.
use the useEffect to get the item from the local storage.
const [user,setUser]=useState(null);
useEffect(()=>{
const currentUser = JSON.parse(localStorage.getItem("auth"));
setUser(currentUser)
},[])
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};

Passing data from one component to another in React using formik

I've created a simple react component for a form with few input fields using formik. My form is rendered three times on my home page for three different type of users, but I only have one button that is outside the component and on click it should save the data inside the PersonalInformation component. This is how my code looks inside my App.js (ignore the users and data for now):
{users.map((data, i) => { return <PersonalInformation key={i} /> })}
<Button>Submit</Button> //this is the button that needs to save the data inside of PersonalInfo component od click
My question is how I can save the data inside the three forms on click on the button? In end-point on the back end I would like to get an array of three objects, each objects will contain info about each field in the form. I guess what I need is to pass data from PersonalInformation component to onClick()event in Button, but I am not sure how to do that with formik.
if you don't use any state management, context etc i think simplest way is you can pass reference to your save method upper.
import React, {useRef} from "react";
import PersonalInformation from "./PersonalInformation";
import "./styles.css";
export default function App() {
const saveRef = useRef(null)
return (
<div className="App">
<PersonalInformation passSave={(ref) => saveRef.current = ref}/>
<button onClick={() => saveRef.current()}> save </button>
</div>
);
}
//---------------------------------------------------------
import React, { useCallback, useEffect, useRef } from "react";
const PersonalInformation = ({passSave}) => {
const formInput = useRef(null);
const save = useCallback(() => {
console.log(formInput.current.value)
}, [formInput])
useEffect(()=>{
passSave(save)
}, [passSave, save])
return (
<input type="text" ref={formInput} />
)
}
export default PersonalInformation;

react memo is not getting props

React memo isn't capturing the props neither the prevProps nor the nextProps and the component render well. The react docs say
If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost.
my problem is to stop twice rendering using react memo, but memo seems to be not working and the component renders twice with the same props.
The component renders when the Create New Event is clicked on /events
here is the live sandbox.
Child Component located at /components/Event/CreateEvent/CreateEvent.js
the parent component is located at /Pages/Event/Event.js line number 999' from where the child component is being triggered
Here is the Code:
import React from "react";
import AuthContext from "../../context/global-context";
import CreateEvent from "../../components/Event/CreateEvent/CreateEvent";
function Events({ location }) {
// Sate Managing
const [allEvents, setAllEvents] = React.useState([]);
const [creating, setCreating] = React.useState(false);
// Context As State
const { token, email } = React.useContext(AuthContext);
// Creating Event Showing
const modelBoxHandler = () => {
// works on when the ViewEvent is open
if (eventSelected) {
setEventSelected(null);
return;
}
setCreating(!creating);
};
return (
<div className="events">
{/* New Event Creating */}
{creating && (
<CreateEvent onHidder={modelBoxHandler} allEvents={allEvents} />
)}
{console.log("Event Rendered.js =>")}
</div>
);
}
export default React.memo(Events, () => true);
Child Component where the Rect memo doesn't have props:
import React from "react";
import AuthContext from "../../../context/global-context";
function CreateEvent({ onHidder, allEvents }) {
// Context
const { token } = React.useContext(AuthContext);
console.log("CreatedEvent.js REnder");
return (
... Some code here
);
}
export default React.memo(CreateEvent, (prevProps, nextProps) => {
console.log("Hello", prevProps, nextProps);
});
Thanks in advance for your valuable answer and times!
The problem is that on basis of creating variable you are actually remounting and not rendering the CreateEvent component. What it means is that if creating variable changes, the component is unmounted and re-mounted when creating is true, so its not a re-render
Also you must note that modelBoxHandler function reference also changes on each re-render so even if your CreateEvent component is in rendered state and the parent re-rendered due to some reason , the CreateEvent component too will re-render
There are 2 changes that you need to make to make it work better
Define modelBoxHandler with a useCallback hook
perform conditional rendering in createEvent based on creating prop
// Creating Event Showing
const modelBoxHandler = useCallback(() => {
// works on when the ViewEvent is open
if (eventSelected) {
setEventSelected(null);
return;
}
setCreating(prevCreating => !prevCreating);
}, [eventSelected]);
...
return (
<div className="events">
{/* New Event Creating */}
<CreateEvent creating={creating} onHidder={modelBoxHandler} allEvents={allEvents} />
{console.log("Event Rendered.js =>")}
</div>
);
and in createEvent
function CreateEvent({ onHidder, allEvents, creating }) {
// Context
const { token } = React.useContext(AuthContext);
console.log("CreatedEvent.js REnder");
if(!creating) {
return null;
}
return (
... Some code here
);
}
export default React.memo(CreateEvent);
In your example, you don't have an additional render for React.memo to work.
According to your render logic, there aren't any nextProps, you unmount the component with conditional rendering (creating).
// You toggle with `creating` value, there is only single render each time
creating && <CreateEvent onHidder={modelBoxHandler} allEvents={allEvents}/>
// Works, because there will be multiple renders (nextProps)
true && <CreateEvent onHidder={modelBoxHandler} allEvents={allEvents} />
In this case, you might not need React.memo.

Conditional rendering in React Native with global variable

I know this is horrible convention, but I'm trying to quickly conditionally render screens in my React Native app with global variables (so no redux):
App.js:
if (global.clickStatus !== 'clicked') {
return <Screen1 />;
}
return <Screen2 />;
The app begins on Screen1, where there is a button that makes global.clickStatus = 'clicked'. When this is clicked, I want Screen2 to render. The problem is, the global.clickStatus doesn't seem to update on my App.js (even though global.clickStatus is changed, it still renders Screen1.
How can I get it to update?
I believe in <App /> component because it is a function component you can introduce a state if your button is clicked. Then with clicked state you can manipulate which component to show.
Similarly like the following - obviously this is a simplified example:
const App = () => {
const [clicked, setClicked] = useState(false);
return <>
<div onClick={() => setClicked(true)}>Click me</div>
{ clicked ? <Screen2 /> : <Screen1 /> }
</>
}
Suggested read is Using the State Hook.
The app begins on Screen1, where there is a button that makes global.clickStatus = 'clicked'
When you click the button, you did not set any state for App.js component => no re-render action is made.
I just assume the button is in Screen 1. Try code below:
import React from "react";
import "./styles.css";
export default function App() {
// Create a state
const [renderIndex, setRenderIndex] = useState(new Date().getTime())
if (global.clickStatus !== 'clicked') {
// Assume you have a button in Screen1
// Pass a callback function from this component to Screen1
// When button in Screen1 is clicked, call this callback function to update renderIndex => App component will re-render
return <Screen1 callBack={() => setRenderIndex(new Date().getTime())}/>;
}
return <Screen2 />;
}

React-Loadable re-rendering causing input to lose focus

I'm having an issue where react-loadable is causing one of my input components to re-render and lose focus after a state update. I've done some digging and I can't find anyone else having this issue, so I think that I'm missing something here.
I am attempting to use react-loadable to dynamically include components into my app based on a theme that the user has selected. This is working fine.
./components/App
import React from 'react';
import Loadable from 'react-loadable';
/**
* Import Containers
*/
import AdminBar from '../../containers/AdminBar';
import AdminPanel from '../../components/AdminPanel';
import 'bootstrap/dist/css/bootstrap.css';
import './styles.css';
const App = ({ isAdmin, inEditMode, theme }) => {
const MainContent = Loadable({
loader: () => import('../../themes/' + theme.name + '/components/MainContent'),
loading: () => (<div>Loading...</div>)
});
const Header = Loadable({
loader: () => import('../../themes/' + theme.name + '/components/Header'),
loading: () => (<div>Loading...</div>)
});
return (
<div>
{
(isAdmin) ? <AdminBar
className='admin-bar'
inEditMode={inEditMode} /> : ''
}
<Header
themeSettings={theme.settings.Header} />
<div className='container-fluid'>
<div className='row'>
{
(isAdmin && inEditMode) ? <AdminPanel
className='admin-panel'
theme={theme} /> : ''
}
<MainContent
inEditMode={inEditMode} />
</div>
</div>
</div>
);
};
export default App;
./components/AdminPanel
import React from 'react';
import Loadable from 'react-loadable';
import './styles.css';
const AdminPanel = ({ theme }) => {
const ThemedSideBar = Loadable({
loader: () => import('../../themes/' + theme.name + '/components/SideBar'),
loading: () => null
});
return (
<div className='col-sm-3 col-md-2 sidebar'>
<ThemedSideBar
settings={theme.settings} />
</div>
);
};
export default AdminPanel;
This is what my <ThemedSideBar /> components looks like:
./themes/Default/components/SideBar
import React from 'react';
import ThemeSettingPanel from '../../../../components/ThemeSettingPanel';
import ThemeSetting from '../../../../containers/ThemeSetting';
import './styles.css';
const SideBar = ({ settings }) => {
return (
<ThemeSettingPanel
name='Header'>
<ThemeSetting
name='Background Color'
setting={settings.Header}
type='text'
parent='Header' />
<ThemeSetting
name='Height'
setting={settings.Header}
type='text'
parent='Header' />
</ThemeSettingPanel>
);
};
export default SideBar;
./components/ThemeSettingPanel
import React from 'react';
import { PanelGroup, Panel } from 'react-bootstrap';
const ThemeSettingPanel = ({ name, children }) => {
return (
<PanelGroup accordion id='sidebar-accordion-panelGroup'>
<Panel>
<Panel.Heading>
<Panel.Title toggle>{name}</Panel.Title>
</Panel.Heading>
<Panel.Body collapsible>
{children}
</Panel.Body>
</Panel>
</PanelGroup>
);
};
export default ThemeSettingPanel;
./containers/ThemeSetting
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { themeSettingChange } from '../App/actions';
import ThemeSetting from '../../components/ThemeSetting';
class ThemeSettingContainer extends Component {
constructor(props) {
super(props);
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange(name, parent, value) {
const payload = {
name: name,
parent,
value: value
};
this.props.themeSettingChange(payload);
}
render() {
return (
<ThemeSetting
name={this.props.name}
setting={this.props.setting}
parent={this.props.parent}
type={this.props.type}
handleOnChange={this.handleOnChange} />
);
}
}
//----Redux Mappings----//
const mapStateToProps = (state) => ({
});
const mapDispatchToProps = {
themeSettingChange: (value) => themeSettingChange(value)
};
export default connect(mapStateToProps, mapDispatchToProps)(ThemeSettingContainer);
./component/ThemeSetting
import React from 'react';
import TextField from '../common/TextField';
import './styles.css';
const ThemeSetting = ({ name, setting, type, parent, handleOnChange }) => {
return (
<div className='row theme-setting'>
<div className='col-xs-7'>
{name}
</div>
<div className='col-xs-5'>
{
generateField(type, setting, name, parent, handleOnChange)
}
</div>
</div>
);
};
function generateField(type, setting, name, parent, handleOnChange) {
const value = setting ? setting[name] : '';
switch (type) {
case 'text':
return <TextField
value={value}
name={name}
parent={parent}
handleOnChange={handleOnChange} />;
default:
break;
}
}
export default ThemeSetting;
./components/common/TextField
import React from 'react';
import { FormControl } from 'react-bootstrap';
const TextField = ({ value, name, parent, handleOnChange }) => {
return (
<FormControl
type='text'
value={value}
onChange={(e) => {
handleOnChange(name, parent, e.target.value);
}} />
);
};
export default TextField;
When a field inside of my Admin Panel is updated, a state change is triggered. It seems like this triggers react-loadable to re-render my <ThemedSideBar /> components which destroys my input and creates a new one with the updated value. Has anyone else had this issue? Is there a way to stop react-loadable from re-rendering?
EDIT: Here is the requested link to the repo.
EDIT: As per conversation in the comments, my apologies, I misread the question. Answer here is updated (original answer below updated answer)
Updated answer
From looking at the react-loadable docs, it appears that the Loadable HOC is intended to be called outside of a render method. In your case, you are loading ThemedSideBar in the render method of AdminPanel. I suspect that the change in your TextEdit's input, passed to update your Redux state, and then passed back through the chain of components was causing React to consider re-rendering AdminPanel. Because your call to Loadable was inside the render method (i.e. AdminPanel is a presentational component), react-loadable was presenting a brand new loaded component every time React hit that code path. Thus, React thinks it needs to destroy the prior component to appropriately bring the components up to date with the new props.
This works:
import React from 'react';
import Loadable from 'react-loadable';
import './styles.css';
const ThemedSideBar = Loadable({
loader: () => import('../../themes/Default/components/SideBar'),
loading: () => null
});
const AdminPanel = ({ theme }) => {
return (
<div className='col-sm-3 col-md-2 sidebar'>
<ThemedSideBar
settings={theme.settings} />
</div>
);
};
export default AdminPanel;
Original answer
It seems that your problem is likely related to the way you've built TextField and not react-loadable.
The FormControl is taking value={value} and the onChange handler as props. This means you've indicated it is a controlled (as opposed to uncontrolled) component.
If you want the field to take on an updated value when the user types input, you need to propagate the change caught by your onChange handler and make sure it gets fed back to the value in the value={value} prop.
Right now, it looks like value will always be equal to theme.settings.Height or the like (which is presumably null/empty).
An alternative would be to make that FormControl an uncontrolled component, but I'm guessing you don't want to do that.

Categories