I have a similar situation like the one in the sandbox.
https://codesandbox.io/s/react-typescript-fs0em
Basically what I want to achieve is that Table.tsx is my base component and App component is acting like a wrapper component. I am returning the JSX from the wrapper file.
Everything is fine but the problem is whenever I hover over any name, getData() is called and that is too much rerendering. Here it is a simple example but in my case, in real, the records are more.
Basically Table is a generic component which can be used by any other component and the data to be displayed in can vary. For e.g. rn App is returning name and image. Some other component can use the Table.tsx component to display name, email, and address. Think of App component as a wrapper.
How can I avoid this getData() to not to be called again and again on hover?
Can I use useMemo or what approach should I use to avoid this?
Please help
Every time you update the "hover" index state in Table.jsx it rerenders, i.e. the entire table it mapped again. This also is regenerating the table row JSX each time, thus why you see the log "getData called!" so much.
You've effectively created your own list renderer, and getData is your "renderRow" function. IMO Table shouldn't have any state and the component being rendered via getData should handle its own hover state.
Create some "row component", i.e. the thing you want to render per element in the data array, that handles it's own hover state, so when updating state it only rerenders itself.
const RowComponent = ({ index, name }) => {
const [hov, setHov] = useState();
return (
<div
key={name}
onMouseEnter={() => setHov(index)}
onMouseLeave={() => setHov(undefined)}
style={{ display: "flex", justifyContent: "space-around" }}
>
<div> {name} </div>
<div>
<img
src={hov === index ? img2 : img1}
height="30px"
width="30px"
alt=""
/>
</div>
</div>
);
};
Table.jsx should now only take a data prop and a callback function to render a specific element, getData.
interface Props {
data: string[];
getData: () => JSX.Element;
}
export const Table: React.FC<Props> = ({ data, getData }) => {
return (
<div>
{data.map((name: string, index: number) => getData(name, index))}
</div>
);
};
App
function App() {
const data = ["Pete", "Peter", "John", "Micheal", "Moss", "Abi"];
const getData = (name: string, index: number, hov: number) => {
console.log("getData called!", index);
return <RowComponent name={name} index={index} />;
};
return <Table data={data} getData={getData} />;
}
Related
So for example:
{!loading ? (data.map((v, i) => {
return <Card key={i} title={v.name} image={v.pictures.sizes[4].link}} /> })
Now these cards show up as a stack of components on the main paing. In each card, there is a button. when I click that button it changes a state in the Card. How can I get that button to cause the Card I click to leave the main screen immediately without needing to reload everything?
I've tried quite a bit and nothing has worked--> Ive tried passed a parent state function, and dealing with the state inside the child
You need to move the state out of the Card and into the parent component. Then you can pass in a function as a prop to each Card component which can then be called on the button onClick function
export const Table = () => {
const [cards, setCards] = useState<Array<{id:string; name: string; pictures: any;}>>([]); // put your card data in here
const removeCard = (id: string) => setCards(prev => prev.filter(card => card.id !== id));
return (
<>
{cards.map(card => <Card key={card.id} id={card.id} title={card.name} image={card.pictures.sizes[4].link} remove={removeCard} />)}
</>
)
}
I have a component which has child components, i want to render these child components with different Ids. They are getting their data from store.The problem is they are rendered but with the same item. how can this be solved?
MultiImages Component
const MultiImages: () => JSX.Element = () => {
const values = ['500', '406', '614'];
return (
<div>
{values.map((val, index) => {
return <OneImage key={index} projectID={val} />;
})}
</div>
);
};
export default MultiImages;
OneImage Component
const OneImage: () => JSX.Element = ({ projectID }) => {
const projectData = useProjectDataStore();
const { getProject } = useAction();
useEffect(() => {
getProject(projectID ?? '');
}, []);
return (
<>
<div>
<img
src={projectData.picture}
}
/>
<div>
<a>
{projectData.projectName}
</a>
</div>
</div>
</>
);
};
export default OneImage;
Your issue here - you are calling in a loop, one by one fetch your projects, and each call, as far as we can understand from your example and comments override each other.
Your are doing it implicitly, cause your fetching functionality is inside your Item Component OneImage
In general, the way you are using global state and trying to isolate one from another nodes is nice, you need to think about your selector hook.
I suggest you, to prevent rewriting too many parts of the code, to change a bit your selector "useProjectDataStore" and make it depended on "projectID".
Each load of next project with getProject might store into your global state result, but instead of overriding ALL the state object, you might want to use Map(Dictionary) as a data structure, and write a result there and use projectID as a key.
So, in your code the only place what might be change is OneImage component
const OneImage: () => JSX.Element = ({ projectID }) => {
// making your hook depended on **projectID**
const projectData = useProjectDataStore(projectID);
const { getProject } = useAction();
useEffect(() => {
// No need of usage **projectID** cause it will inherit if from useProjectDataStore
getProject();
}, []);
return (
<>
<div>
<img
src={projectData.picture}
}
/>
<div>
<a>
{projectData.projectName}
</a>
</div>
</div>
</>
);
};
export default OneImage;
And inside of your useProjectDataStore store result into a specific key using projectID.
Your component OneImage will return what's in the return statement, in your case:
<>
<div>
<img
src={projectData.picture}
/>
<div>
<a>
{projectData.projectName}
</a>
</div>
</div>
</>
This tag <></> around your element is a React.fragment and has no key. This is the reason you get this error.
Since you already have a div tag wrapping your element you can do this:
<div key={parseInt(projectID)}>
<img
src={projectData.picture}
/>
<div>
<a>
{projectData.projectName}
</a>
</div>
</div>
You can also change the key to Math.floor(Math.random() * 9999).
Note that passing the prop key={index} is unnecessary, and is not advised to use index as keys in a react list.
Looking for some guidance on how to structure the below components to trigger an (export) method in one component from another 'sibling' component.
Using a download button contained in <DownloadChartButton> in the Card Header, I want to download a chart contained in my PaginatedRechartsChart component as a PNG. I currently have the components structured like below. DownloadChartButton needs to access the recharts chart contained in my <PaginatedRechartsChart> component. Hoping to keep DashboardCard, DownloadChartButton, and PaginatedRechartsChart generic so they can be applied in many places, hence the current structure.
Question: Is there a better way to structure my components to avoid the React anti-pattern of triggering child methods from parent components?
Thank you for your help!
Pseudo-code:
export const LineChartByDay = () => {
const [data, setData] = React.useState([{'date':'2021-01-01': 'count':34})
return (
<DashboardCard
headerItems={<DownloadChartButton data={data}/>}
>
<PaginatedRechartsChart data={data}/>
</DashboardCard>
)
}
import {LineChart} from 'recharts'
export const PaginatedRechartsChart = (data) => {
// ... extra code for client-side pagination, etc.
return (
<ResponsiveContainer>
<LineChart data={data}/>
</ResponsiveContainer>
)
}
export const DashboardCard = ({ title, actions, children, error, loading }: { title: string, actions?: React.ReactNode, children?: React.ReactNode, error?: any, loading?: boolean }) =\> {
return (
<Card>
<CardHeader
title={title}
action={actions}
></CardHeader>
<CardContent>
{error && <ErrorAlertBar title={error}/>}
{loading && <CircularProgress/>}
{children}
</CardContent>
</Card>
)
}
export const DownloadChartButton = (data) => {
// ... CSV download logic (takes a list of objects in data, exports to CSV)
// ... PNG download logic
const [getPng, { ref }] = useCurrentPng();
//Ideally we'd have chart download logic in this component so we don't have to copy it into every chart component
const handleDownload = React.useCallback(async () => {
const png = await getPng();
// Verify that png is not undefined
if (png) {
// Download with FileSaver
FileSaver.saveAs(png, 'myChart.png');
}
}, [getPng]);
return (
<MenuButton>
<MenuItem>CSV</MenuItem>
<MenuItem>PNG</MenuItem>
</MenuButton>
)
}
From what I see online, my current thought is using a ref in the parent component and passing that to PaginatedRechartsChart and DownloadChartButton... but I'm seeing online that this is an anti-pattern for React (i.e. https://stackoverflow.com/a/37950970/20391795)
I am writing a ControlledInput component, and in order to have access to the state of the component using ControlledInput, I have a binder prop in ControlledInput.
I'm having a slight issue when using the component:
render() {
const CI = props => <ControlledInput binder={this} {...props} />;
return (
<div style={styles.container}>
<h1>NEW RECIPE</h1>
<ControlledInput binder={this} label={"Title"} />
</div>
);
}
The implementation above works completely fine. However, note the const CI I've defined. I tried to use this so I could just write <CI label={"Title"}/> without the binder since the binder will be the same on all the ControlledInput components I use in a given render method.
The problem with using <CI label={"Title"}/> is that when I type into the input, the input "blurs" and I have to reselect it. This appears to be because the render method creates the CI on every render.
I hope I've explained that clearly, because my head hurts.
Anyway, it makes sense to me why this happens. And I know that one solution is to put const CI = props => <ControlledInput binder={this} {...props} />; outside of the render function. But then I'd have to call it as <this.CI> and that starts to defeat the purpose.
And I can't put CI in global scope because then I don't have access to this.
Is there a way to solve this?
Update
Here is the current (very much in progress) code for ControlledInput:
// #flow
import React, { Component } from "react";
type Props = {
containerStyle?: Object,
label: string,
propName?: string,
binder: Component<Object, Object>,
onChange?: Object => void
};
class ControlledInput extends Component<Props> {
render() {
const props = this.props;
const propName = props.propName || props.label.toLowerCase();
return (
<div style={props.containerStyle}>
<p>{props.label}</p>
<input
type="text"
label={props.label}
onChange={
this.props.onChange ||
(e => {
props.binder.setState({ [propName]: e.target.value });
})
}
value={props.binder.state[propName]}
></input>
</div>
);
}
}
The point of this whole endeavor is to simplify creating a form with controlled components, avoiding having to add value={this.state.whatever} and onChange={e=>this.setState({whatever: e})} to each one, which is not DRY in my opinion.
And then I want get a little more DRY by not passing binder={this} to every component and that's why I'm doing const CI = props => <ControlledInput binder={this} {...props} />;, which, again, has to be inside the class to access this and inside the render function to be called as CI rather than this.CI.
So that first explanation why you need to pass this, although I suppose I could also have props like setState={this.setState} parentState={this.state}, and in that case it does indeed start to make sense to combine those into something like {...propsToSend} as #John Ruddell suggested.
Note that I've provided a possibility to override onChange, and plan on doing so for most or all of the other props (e.g, value={this.props.value || binder.state[propName]}. If one were to override a lot of these (especially value and onChange) it would indeed make the component much less reusable, but the main use case is for quickly creating multiple inputs that don't have special input handling.
So, again, my ideal would be to call <ControlledInput label="Title"/> and have the component code take care of binding state and setState correctly. If this is possible. And then the second option would be to have a place to define the necessary context props in a place that makes it simple when it's time to actually use the component multiple times, like so:
<ControlledInput label={"title"} {...contextProps}/>
<ControlledInput label={"author"} {...contextProps}/>
<ControlledInput label={"email"} {...contextProps}/>
<ControlledInput label={"content"} textArea={true} {...contextProps}/> // textarea prop not implemented yet, fyi
etc
I hear that accessing the parent state/context may be an anti-pattern, but there must be some way to do what I'm trying to do without using an anti-pattern, isn't there?
If you want the state of the parent, handle the state there and pass down the value to your input - ControlledInput won't have to know anything except how to handle data in and out. Something like this, and note that I jacked up the names a little so you can see which component is handling what:
import React, { useState } from "react"
const Parent = () => {
const [title, setTitle] = useState("")
const handleChangeInParent = (newTitle) => {
setTitle((oldValue) => newTitle)
}
return(<div style={styles.container}>
<h1>NEW RECIPE</h1>
<ControlledInput handleChange={handleChangeInParent} label={title} />
</div>)
}
const ControlledInput = ({handleChange, label}) => {
return (
<input onChange={handleChange} type="text" value={label} />
)
}
If ControlledComponent needs to handle its own state, then pass it a default value and then have the Parent read the value when saving (or whatever):
import React, { useState } from "react"
const Parent = () => {
const handleSaveInParent = (newTitle) => {
console.log("got the new title!")
}
return (
<div style={styles.container}>
<h1>NEW RECIPE</h1>
<ControlledInput handleSave={handleSaveInParent} initialLabel="Title" />
</div>
)
}
const ControlledInput = ({ handleSave, initialLabel }) => {
const [title, setTitle] = useState(initialLabel)
const handleChange = (ev) => {
const value = ev.target.value
setTitle((oldValue) => value)
}
const handleSubmit = (ev) => {
ev.preventDefault()
handleSave(title)
}
return (
<form onSubmit={handleSubmit}>
<input onChange={handleChange} type="text" value={title} />
</form>
)
}
You shouldn't be sending this through - just send values and/or functions to handle values.
With Updated Implementation
(okay, John you win!)
Not positive if this is technically an "answer", but I've rewritten the component to take a state and (updated) a setterFn prop:
component
// #flow
import React, { Component } from "react";
type Props = {
containerStyle?: Object,
labelStyle?: Object,
label: string,
propName?: string,
state: Object,
onChange?: Object => void,
textArea?: boolean,
setterFn: (key: string, value: mixed) => void
};
class ControlledInput extends Component<Props> {
render() {
const props = this.props;
const propertyName = props.propName || props.label.toLowerCase();
const TagType = props.textArea ? "textarea" : "input";
// only pass valid props to DOM element (remove any problematic custom props)
const { setterFn, propName, textArea, ...domProps } = props;
return (
<div style={props.containerStyle}>
<p style={props.labelStyle}>{props.label}</p>
<TagType
{...domProps}
label={props.label} // actually could get passed automatically, but it's important so I'm leaving it in the code
onChange={
this.props.onChange ||
(setterFn ? e => setterFn(propertyName, e.target.value) : null)
}
value={props.state[propertyName] || ""}
></TagType>
</div>
);
}
}
export default ControlledInput;
in use (somehow less code than before!)
class Wrapper extends Component<Object, Object> {
state = {};
render() {
const setterFn = (k, v) => this.setState({ [k]: v });
const p = { state: this.state, setterFn: setterFn.bind(this) };
return <ControlledInput {...p} {...this.props.inputProps} />
}
}
I guess this is more appropriate. It still takes up a lot more space than binder={this}.
It doesn't actually the questions of:
How to access the parent's state from the component. Though from comments it seems like this is an anti-pattern, which I do understand from the theory of React.
How to set these repeating props elsewhere so that I can just call `. I guess the only solution is to do something like this:
render() {
const props = {state: this.state, setState: this.setState}
<ControlledInput {...props} label="Title"/>
}
Which certainly isn't such a bad solution. Especially if I shorten that name to, say, a single character.
Much thanks to #John Ruddell for setting me on the right path.
With react-semantic-ui, I made a searchable, paginationable Table React Component
working example: https://codesandbox.io/s/23q6vlywy
Usage
<PaginationTable
items={[
{
id: 1,
name: "test-item-1 ???"
},
{
id: 2,
name: "test-item-2"
},
{
id: 3,
name: "test-item-3"
}
]}
columnOption={[
{
header: "idHeader",
cellValue: "id",
onItemClick: item => {
alert(item.id);
},
sortingField: "id"
},
{
header: "Name~",
cellValue: item =>
`*custom text cannot be searched* property can item.name => ${
item.name
} `,
onItemClick: item => {
alert(item.name);
},
sortingField: "name"
}
]}
initSortingField={"id"}
initSortingOrderAsc={false}
pagination
itemsPerPage={2}
searchKeyProperties={["id", "name"]}
/>
But this component currently can only have a certain order
1.SearchBar on top
2.Table on middle
3.PaginationBar on bottom
And actually, I didn't write 3 child components in the Component, SearchBar, Table, PaginationBar
So it's hard for me to rewrite it to render props way to change the order such as below
<PaginationTable {...props}>
{({ SearchBar, Table, PaginationBar })=>
<div>
<SearchBar />
<Table />
<SearchBar />
</PaginationTable>
</div>
</PaginationTable>
Because when I tried to change to render props, I first have to write 3 components independently, which means I have to change all variables under this( this.state, this.props, this.xxxFunction ) to something else.
For example:
In , I can use
<Input onChange={()=>{
this.setState({ searchBarText: e.target.value });
}}/>
But If I change it to 3 components, I have to rewrite it to something like
const SearchBar = ({onTextChange}) => <Input onChange=
{onTextChange}/>
<SearchBar onTextChange={()=>{
this.setState({
searchBarText: e.target.value
});
}} />
Is there any way I can adjust child components order elegantly or is there any way I can write render props easier?
Updated # 2018.10.27 17:36 +08:00
I modified <PaginationTable>'s render function as below but it will be lost mouse cursor focus when typing on <SearchInput>
render(){
const SearchBar = ()= (<Input onChange={()=>{...} />);
const TableElement = ()=>(<Table {...} > ... </Table>);
const PaginationBar = ()=>(<Menu {...} > ... </Menu>);
enter code here
return(
<React.Fragment>
{this.props.children({ SearchBar,TableElement, PaginationBar })}
</React.Fragment>)};
Then I found out, in this way, DOM will update every time when my state updated because every render will make a new component reference by const SearchBar = ()=>(...).
Thanks to #Ralph Najm
If I declare child component as below, DOM will not update every time.
render(){
const SearchBar = (<input onChange={...} />);
const TableElement = (<Table .../>);
const PaginationBar = (<Menu .../>);
//... same as above
}
In this way, I can change my component to render props in order to arrange the order very easily.
Thanks in advance.
In the PaginationTable component change your render function and before the return statement, assign the elements to variables (SearchBar, Table, PaginationBar, etc...) then just reference those variables in the render function.
I modified your example here https://codesandbox.io/s/vy4799zp45