I am trying to render a list of components in order with react, the component is updating this array of elements but is not re-ordering them.
Pseudo code;
class Form extends Component {
//
// .... other initialization code and logic
//
updatePositions() {
//
// re-order this.state.page.page_contents
//
this.setState({ page: this.state.page });
}
renderContents() {
return this.state.page.page_content.map((c, i) => {
return (<ContentItem
key={ i }
content={ c }
/>);
});
}
render() {
return (
<div className="row">
<div className="medium-12 columns">
{ this.renderContents() }
</div>
</div>
);
}
}
If i log out the results of page.page_content the items are being reordered in the array, however the form render is not re-rendering the contents in its new order
You shouldn't be using array indices as keys if your array order is subject to change. Keys should be permanent, because React uses the keys to identify the components, and if a component receives a key that previously belonged to a different component, React thinks it is the same component as before.
Create unique keys for your elements that are permanent to those elements.
you could try to force update
renderContents() {
this.forceUpdate();
return this.state.page.page_content.map((c, i) => {
return (<ContentItem
key={ i }
content={ c }
/>);
});
}
Don't mutate this.state, directly. Bring it into a new variable and then add it back into state.
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
from: https://reactjs.org/docs/react-component.html
Instead, you should try:
updatePositions() {
const page_contents = [...this.state.page.page_contents]
// re order page_contents
this.setState({ page: { page_contents });
}
renderContents() {
return this.state.page.page_content.map((c, i) => {
return (<ContentItem
key={ i }
content={ c }
/>);
});
}
it's your code here - key={i} i is not changing so it will not re-render the component - if you want to re-render the component - please make sure that - key should change.
renderContents() {
return this.state.page.page_content.map(c => {
return (<ContentItem
key={ c }
content={ c }
/>);
});
}
c is content - if it's change then Component will re-render
this.setState({ page: this.state.page }) it's wrong - ur trying to set the same value in same variable again .
class Form extends Component {
//
// .... other initialization code and logic
//
updatePositions() {
//
// re-order this.state.page.page_contents
//
this.setState({ page: newValueFromAPI.page });
}
render() {
const { page: { page_content } } = this.state
return (
<div className="row">
<div className="medium-12 columns">
{ page_content.length > 0 && (
page_content.map(c => <ContentItem key={c} content={c}/>)
)}
</div>
</div>
);
}
}
Related
My React component uses apollo to fetch data via graphql
class PopUpForm extends React.Component {
constructor () {
super()
this.state = {
shoptitle: "UpdateMe",
popupbodyDesc: "UpdateMe"
}
}
render()
{
return (
<>
<Query query={STORE_META}>
{({ data, loading, error, refetch }) => {
if (loading) return <div>Loading…</div>;
if (error) return <div>{error.message}</div>;
if (!data) return (
<p>Could not find metafields :(</p>
);
console.log(data);
//loop over data
var loopedmetafields = data.shop.metafields.edges
console.log(loopedmetafields)
loopedmetafields.forEach(element => {
console.log(element.node.value)
if (element.node.value === "ExtraShopDescription"){
this.setState({
shoptitle: element.node.value
});
console.log(this.state.shoptitle)
}
if (element.node.value === "bodyDesc"){
this.setState({
popupbodyDesc: element.node.value
});
console.log(this.state.popupbodyDesc)
}
});
return (
<>
<AddTodo mkey="ExtraShopDesc" namespace="ExtraShopDescription" desc={this.state.shoptitle} onUpdate={refetch} />
<AddTodo mkey="body" namespace="bodyDesc" desc={this.state.popupbodyDesc} onUpdate={refetch} />
</>
);
}}
</Query>
</>
)
}
}
export default PopUpForm
Frustratingly the functional component renders before the state is set from the query. Ideally the functional component would only render after this as I thought was baked into the apollo library but seems I was mistaken and it seems to execute synchronous rather than asynchronous
As you can see I pass the props to the child component, in the child component I use these to show the current value that someone might amend
The functional component is here
function AddTodo(props) {
let input;
const [desc, setDesc] = useState(props.desc);
//console.log(desc)
useEffect( () => {
console.log('props updated');
console.log(props)
}, [props.desc])
const [addTodo, { data, loading, error }] = useMutation(UPDATE_TEXT, {
refetchQueries: [
'STORE_META' // Query name
],
});
//console.log(data)
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
return (
<div>
<form
onSubmit={e => {
console.log(input.value)
setDesc(input.value)
e.preventDefault();
const newmetafields = {
key: props.mkey,
namespace: props.namespace,
ownerId: "gid://shopify/Shop/55595073672",
type: "single_line_text_field",
value: input.value
}
addTodo({ variables: { metafields: newmetafields } });
input.value = input.value
}}
>
<p>This field denotes the title of your pop-up</p>
<input className="titleInput" defaultValue={desc}
ref={node => {
input = node;
}}
/>
<button className="buttonClick" type="submit">Update</button>
</form>
</div>
);
}
Now I need this component to update when the setState is called on PopUpForm
Another stack overflow answer here gives me some clues
Passing the intial state to a component as a prop is an anti-pattern
because the getInitialState (in our case the constuctor) method is
only called the first time the component renders. Never more. Meaning
that, if you re-render that component passing a different value as a
prop, the component will not react accordingly, because the component
will keep the state from the first time it was rendered. It's very
error prone.
Hence why I then implemented useEffect however the console.log in useEffect is still "updateMe" and not the value as returned from the graphql call.
So where I'm at
I need the render the functional component after the the grapql call
and I've manipulated the data, this seems to be the best approach in terms of design patterns also
or
I need setState to pass/render the functional component with the new value
As an aside if I do this
<AddTodo mkey="ExtraShopDesc" namespace="ExtraShopDescription" desc={data.shop.metafields.edges[0].node.value} onUpdate={refetch} />
It will work but I can't always expect the value to be 0 or 1 as metafields might have already defined
I think there is a simpler way than using setState to solve this. You can for example use find like this:
const shopTitleElement = loopedmetafields.find(element => {
return element.node.value === "ExtraShopDescription"
})
const shopBodyElement = loopedmetafields.find(element => {
return element.node.value === "bodyDesc"
});
return (
<>
<AddTodo mkey="ExtraShopDesc" namespace="ExtraShopDescription" desc={shopTitleElement.node.value} onUpdate={refetch} />
<AddTodo mkey="body" namespace="bodyDesc" desc={shopBodyElement.node.value} onUpdate={refetch} />
</>
);
minimum reproducible example: https://codesandbox.io/s/react-hover-example-tu1eu?file=/index.js
I currently have a new element being rendered when either of 2 other elements are hovered over. But i would like to render different things based upon which element is hovered.
In the example below and in the codepen, there are 2 hoverable divs that are rendered; when they are hovered over, it changes the state and another div is rendered. I would like for the HoverMe2 div to render text "hello2". Currently, whether i hover hoverme1 or 2, they both just render the text "hello".
import React, { Component } from "react";
import { render } from "react-dom";
class HoverExample extends Component {
constructor(props) {
super(props);
this.handleMouseHover = this.handleMouseHover.bind(this);
this.state = {
isHovering: false
};
}
handleMouseHover() {
this.setState(this.toggleHoverState);
}
toggleHoverState(state) {
return {
isHovering: !state.isHovering
};
}
render() {
return (
<div>
<div
onMouseEnter={this.handleMouseHover}
onMouseLeave={this.handleMouseHover}
>
Hover Me
</div>
<div
onMouseEnter={this.handleMouseHover}
onMouseLeave={this.handleMouseHover}
>
Hover Me2
</div>
{this.state.isHovering && <div>hello</div>}
</div>
);
}
}
render(<HoverExample />, document.getElementById("root"));
You need to keep the state of item which you have hovered that's for sure
const { Component, useState, useEffect } = React;
class HoverExample extends Component {
constructor(props) {
super(props);
this.handleMouseHover = this.handleMouseHover.bind(this);
this.state = {
isHovering: false,
values: ['hello', 'hello2'],
value: 'hello'
};
}
handleMouseHover({target: {dataset: {id}}}) {
this.setState(state => {
return {
...state,
isHovering: !state.isHovering,
value: state.values[id]
};
});
}
render() {
return (
<div>
<div
data-id="0"
onMouseEnter={this.handleMouseHover}
onMouseLeave={this.handleMouseHover}
>
Hover Me
</div>
<div
data-id="1"
onMouseEnter={this.handleMouseHover}
onMouseLeave={this.handleMouseHover}
>
Hover Me2
</div>
{this.state.isHovering && <div>{this.state.value}</div>}
</div>
);
}
}
ReactDOM.render(
<HoverExample />,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<div id="root"></div>
You can pass the context text as shown in example. This is working code:
import React, { Component } from "react";
import { render } from "react-dom";
// Drive this using some configuration. You can set based on your requirement.
export const HOVER_Hello1 = "Hello1";
export const HOVER_Hello2 = "Hello2";
class HoverExample extends Component {
constructor(props) {
super(props);
this.handleMouseHover = this.handleMouseHover.bind(this);
this.state = {
isHovering: false,
contextText: ""
};
}
handleMouseHover = (e, currentText) => {
this.setState({
isHovering: !this.state.isHovering,
contextText: currentText
});
}
toggleHoverState(state) {
//
}
render() {
return (
<div>
<div
onMouseEnter={e => this.handleMouseHover(e, HOVER_Hello1)}
onMouseLeave={e => this.handleMouseHover(e, HOVER_Hello1)}
>
Hover Me
</div>
<div
onMouseEnter={e => this.handleMouseHover(e, HOVER_Hello2)}
onMouseLeave={e => this.handleMouseHover(e, HOVER_Hello2)}
>
Hover Me2
</div>
{this.state.isHovering && <div>{this.state.contextText}</div>}
</div>
);
}
}
export default HoverExample;
If the whole point is about linking dynamically messages to JSX-element you're hovering, you may store that binding (e.g. within an object).
Upon rendering, you simply pass some anchor (e.g. id property of corresponding object) within a custom attribute (data-*), so that later on you may retrieve that, look up for the matching object, put linked message into state and render the message.
Following is a quick demo:
const { Component } = React,
{ render } = ReactDOM,
rootNode = document.getElementById('root')
const data = [
{id:0, text: 'Hover me', message: 'Thanks for hovering'},
{id:1, text: 'Hover me too', message: 'Great job'}
]
class HoverableDivs extends Component {
state = {
messageToShow: null
}
enterHandler = ({target:{dataset:{id:recordId}}}) => {
const {message} = this.props.data.find(({id}) => id == recordId)
this.setState({messageToShow: message})
}
leaveHandler = () => this.setState({messageToShow: null})
render(){
return (
<div>
{
this.props.data.map(({text,id}) => (
<div
key={id}
data-id={id}
onMouseEnter={this.enterHandler}
onMouseLeave={this.leaveHandler}
>
{text}
</div>
))
}
{
this.state.messageToShow && <div>{this.state.messageToShow}</div>
}
</div>
)
}
}
render (
<HoverableDivs {...{data}} />,
rootNode
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
As #CevaComic pointed out, you can do this with CSS. But if you want to use React, for example, because your actual problem is more complex, here is the answer.
You will need a way to tell apart the two elements. It could be done with some neat tricks, like setting an unique id to each element, passing a custom argument, or something else.
But I would advise against "cool tricks" as it's more difficult to understand what is going on, and the code is more prone to errors. I think the best way it to use a dumb approach of unique functions for unique elements.
Each onMouseEnter and onMouseLeave has to be an unique function (e.g. handleMouseHover1 and handleMouseHover2), and each of those functions need to control unique state (for example, isHovering1 and isHovering2). Then you have to render the element you want based on the state. Of course, for a real-world code, you will probably want to use more descriptive names to make the code more comprehensible. The full code would look something like this.
class HoverExample extends Component {
state = {
isHovering1: false,
isHovering2: false
};
handleMouseHover1 = () => {
this.setState(({ isHovering1 }) => ({ isHovering1: !isHovering1 }));
};
handleMouseHover2 = () => {
this.setState(({ isHovering2 }) => ({ isHovering2: !isHovering2 }));
};
render() {
const { isHovering1, isHovering2 } = this.state;
return (
<div>
<div
onMouseEnter={this.handleMouseHover1}
onMouseLeave={this.handleMouseHover1}
>
Hover Me1
</div>
<div
onMouseEnter={this.handleMouseHover2}
onMouseLeave={this.handleMouseHover2}
>
Hover Me2
</div>
{isHovering1 && <div>hello1</div>}
{isHovering2 && <div>hello2</div>}
</div>
);
}
}
Also, updated example: https://codesandbox.io/s/react-hover-example-rc3h0
Note: I have also edited the code to add some syntax sugar which exists with newer ECMAScript versions. Instead of binding the function, you can use the arrow function format, e.g. fn = () => { ... }. The arrow function means the this context is automatically bound to the function, so you don't have to do it manually. Also, you don't have to initialize this.state inside the constructor, you can define it as a class instance property. With those two things together, you do not need the constructor at all, and it makes the code a bit cleaner.
I'm using drag and drop to instantiate react classes, but for some reason the state from the parent component is not being passed to the child. The child isn't even being rerendered, tried shouldComponentUpdate and componentWillReceiveProps.
Parents relevant code:
dragEnd(e) {
e.preventDefault();
let me = this;
let el = (
<Pie key={ Date.now() * Math.random() } yAxisData={ me.state.yAxisData } legendData={ me.state.legendData } />
)
this.setState({
cells: this.state.cells.concat(el),
});
}
So, on drop, is created, and then render looks like:
render() {
<div className = { "insights-data" } onDrop={ this.dragEnd } onDragOver={ this.preventDefault }>
{ this.state.cells }
</div>
}
All this works fine, but now when I change the data passed to this.state.yAxisData and/or this.state.legendData, it's not calling render on the child component.
Here's the child components render:
render() {
return (
<div className="insights-cell">
<ReactECharts
option={ this.create() }
style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0, height: "100%" }}
theme="chalk"
notMerge={ true }
/>
</div>
)
}
Any ideas? I thought maybe there was a binding issue, but that doesn't seem to be it, as I'm using me = this. It's not even re-rendering the child component.
You are already creating the element in dragEnd function by passing props to it and storing them to an array. Therefore the array this.state.cells contain the array of already declared elements. Therefore it cannot update on state change. You should render a new array of element on every render.
Just push some necessary detail of dragged element in this.state.cells and then iterate through this array on every render.
dragEnd(e) {
e.preventDefault();
let el = draggedElementType
this.setState({
cells: this.state.cells.concat(el),
});
}
And in render, iterate through this array and return the desired element.
render() {
<div className = { "insights-data" } onDrop={ this.dragEnd } onDragOver={ this.preventDefault }>
{ this.state.cells.map((cell, index) => {
if (cell === "pie") {
return (<Pie key={index} yAxisData={ me.state.yAxisData } legendData={ me.state.legendData } />);
}
else if (){...
)}
</div>
}
I'm still new to React. I'm trying to render a jsx under a condition defined in another method under my class component like so:
isWinner = () => {
let userVotesCount1 = this.state.user1.userVotesCount;
let userVotesCount2 = this.state.user2.userVotesCount;
if (userVotesCount1 > userVotesCount2) {
userVotesCount1++;
this.setState({ user1: { userVotesCount: userVotesCount1 } });
return (
<h3>Winner</h3>
);
}
userVotesCount2++;
this.setState({ user2: { userVotesCount: userVotesCount2 } });
return (
<h3>Loser</h3>
);}
and i'm calling this method inside the render method
<Dialog
open={open}
onRequestClose={this.onClose}
>
<div>
<isWinner />
</div>
</Dialog>
already tried to use replace <isWinner /> for {() => this.isWinner()}and I never get the return from the method. What I am doing wrong? Since I'm dealing with state here I wouldn't know how to do this with outside functions. For some reason this function is not being called ever. Please help!
You're almost there. What you want to do is use the method to set a flag, and then use the flag in the render method to conditionally render.
constructor(props) {
...
this.state = {
isWinner: false,
...
}
}
isWinner() {
...,
const isWinner = __predicate__ ? true : false;
this.setState({
isWinner: isWinner
});
}
render() {
const { isWinner } = this.state;
return isWinner ? (
// jsx to return for winners
) : (
// jsx to return for lossers
)
}
I have a component called <SiteMenu />. Inside of my render function I have these three lines:
render() {
{ this.renderPrimaryMenu() }
{ secondaryMenuContents && this.renderSecondaryMenu() }
{ this.renderAdditional() }
}
Each of those have a corresponding function that maps through results and creates menus as unordered list. A boiled-down version:
renderAdditional() {
const { secondaryMenuContents } = this.props;
if (!secondaryMenuContents) { return false; }
const additional = filter(secondaryMenuContents.sections, { additional: true });
if (!additional || additional.length === 0) { return false; }
const links = additional.map(
(link, index) => {
return (
<Link
key={ `${index}-${link.link}` }
to: link.link
>
{ link.text }
</Link>
);
}
);
return (
<nav className={ styles['nav--additional'] }>
<Responsive>
<h3 className={ styles.h3 }>{ Lang.additionalSection.title }</h3>
<menu className={ styles['menu--additional'] }>
{ links }
</menu>
</Responsive>
</nav>
);
}
Each time one of these lists is rendered it re-renders the entire component. One of the menus uses static JSON (renderPrimaryMenu()) while the other two depend on data in two separate calls from an API, so that data doesn’t always come in at the same time.
Any suggestions for ensuring a single render OR, even better, having the first static menu (which fades in and re-fades in with every render) display and the other two render when they’re ready without causing the first menu to re-render?
Appreciate any help I can get!
I suggest you to separate these three components.
And use shouldComponentUpdate() to ensure whether to rerender the component.
This is the pseudo-code:
class PrimaryMenu extends Component {
shouldComponentUpdate() {
// if data is the same, return false
// else return true
}
render() {
return (
...
)
}
}
class SecondaryContent extends Component {
// same logic as PrimaryMenu
}
class Additional extends Component {
// same logic as PrimaryMenu
}
class SiteMenu extends Component {
render() {
return (
<PrimaryMenu/>
<SecondaryContent/>
<Additional/>
)
}
}
So with this setup, you can control the re-render time at each Menu.
or try PureComponent, it exists to reduce re-rendering stuff.
import React, { PureComponent } from 'react';
class Additional extends PureComponent {
}
More info
https://reactjs.org/docs/react-api.html#reactpurecomponent