Passing array of object into functional component and mapping - reactjs

I'm trying to use Material UI to create a reusable navigation tab, however, I am having trouble passing the object over to my functional component and mapping it out. Nothing displays when mapping.
I am fairly new to react hooks. Thanks in advance.
Class Component (passing state over to Navigation)
class MyWorkspace extends Component {
state = {
menuItem: [
{
name: "menu 01",
urlPath: "/home/menu01"
},
{
name: "menu 02",
urlPath: "/home/menu02"
},
{
name: "Reports",
urlPath: "/home/menu03"
},
],
}
}
render () {
return (
<div>
<Navigation menuItem />
</div>
)
}
Functional Component
export default function Navigation({ menuItem }) {
const [value, setValue] = React.useState(2);
const handleChange = (event, newValue) => {
setValue(newValue);
};
const MenuList = () => {
return (
<>
{menuItem.map(item => {
return <Tab label={item.name} className="Nav-Tab" />;
})}
</>
)
}
return (
<div className="Nav-Title row">
<Tabs
className="Nav-Tab-List"
value={value}
indicatorColor="primary"
textColor="primary"
onChange={handleChange}
>
<MenuList />
</Tabs>
</div>
);
}

In the class component, you should assign a value to the prop being passed:
render () {
return (
<div>
<Navigation menuItem={this.state.menuItem} />
</div>
)
}
In function component, you should call MenuList() inside the render :
export default function Navigation({ menuItem }) {
const [value, setValue] = React.useState(2);
const handleChange = (event, newValue) => {
setValue(newValue);
};
const MenuList = () => {
return (
<>
{menuItem.map(item => {
return <Tab label={item.name} className="Nav-Tab" />;
})}
</>
)
}
return (
<div className="Nav-Title row">
<Tabs
className="Nav-Tab-List"
value={value}
indicatorColor="primary"
textColor="primary"
onChange={handleChange}
>
{MenuList()} // call this or put the map here
</Tabs>
</div>
);
}

First you need to define state in constructor
Second destruct menuitem from state
const {menuItem} = this.state
Third pass props like this
<Navigation menuItem={menuItem} />
If you pass like this Navigation menuItem /> you will get boolean value true inside child component.

In MyWorkspace/render function, you don't actually pass the menuItem state.
<Navigation menuItem /> will pass menuItem as true value. Replace it with: <Navigation menuItem={this.state.menuItem} />
Navigation component code looks correct

Related

Passing function props to children in React

I want to use handleChange in the <Tab/> component but couldn't get it done.
const handleChange = (event, newValue) => {
setValue(newValue)
}
How can I access onChange prop on <Tab/> component?
<TabHeader value={value} onChange={handleChange}>
<Tab label="Tab1" />
<Tab label="Tab2" />
<Tab label="Tab2" />
</TabHeader>
Here's my <TabHeader/> component:
function TabHeader(props) {
const { children, value, onChange, ...other } = props
return (
<ul>
{children} <--- Tab components
</ul>
)
}
Have you tried cloneElement?
function TabHeader(props) {
const { children, onChange } = props;
const childWithProps = Children.map(children, (child) =>
isValidElement(child) ? cloneElement(child, { onChange }) : null
);
return <ul>{childWithProps}</ul>;
}
Working solution can be found here: https://codesandbox.io/s/suspicious-dawn-h56von?file=/src/App.js:514-754
Ref: How to pass props to {this.props.children}

React onClick to affect only this iteration

I have a page that uses an object that contains lists within lists. I have all the components showing the data correctly, but I'm trying to add a toggle button for each primary list item so you can show/hide their child lists. I had previously made something that would affect EVERY instance of the component when clicked, so when you click the expand button it would toggle the child lists of EVERY primary item.
React is new to me and I'm using this project partially as a learning tool. I believe this has to do with binding state to the specific instance of the component, but I'm not sure how or where to do this.
Here is the component:
const SummaryItem = props => {
const summary = props.object;
return(
<div className="summary_item">
{Object.entries(summary).map( item =>
<div>
Source: {item[0]} <br />
Count: {item[1].count} <br />
<button onClick={/*expand only this SummaryItemList component*/}>expand</button>
<SummaryItemList list={item[1].items} />
</div>)
}
</div>
);
}
I previously had a state hook that looked like:
const [isExpanded, setIsExpanded] = useState(false);
const toggle = () => setIsExpanded(!isExpanded);
And in my render function the button had the toggle function in the onClick:
<button onClick={toggle}>expand</button> and I had a conditional if(isExpanded) with two renders, one with the SummaryItemList component and one without.
Is there a better way to do this besides mapping the object, and how do I bind the state of the toggle to affect only the instance it's supposed to affect?
I think you maybe forgot to give each item an isExpanded, the best way to do this is to split up your items and item in different components (in the example below it List for items and Item for item).
const { useState } = React;
const Item = ({ name, items }) => {
const [isExpanded, setIsExpanded] = useState(false);
const toggle = () => {
setIsExpanded((s) => !s);
};
return (
<li>
{name}
{items && (
<React.Fragment>
<button onClick={toggle}>
{isExpanded ? '-' : '+'}
</button>
{isExpanded && <List data={items} />}
</React.Fragment>
)}
</li>
);
};
const List = ({ data }) => {
return !data ? null : (
<ul>
{Object.entries(data).map(([key, { items }]) => (
<Item key={key} items={items} name={key} />
))}
</ul>
);
};
const App = () => {
const data = {
A: {
items: {
AA1: { items: { AAA1: {}, AAA2: {} } },
AA2: { items: { AAA: {} } },
},
},
};
return <List data={data} />;
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Update state from deeply nested component without re-rendering parents

I have a form page structured more or less as follows:
<Layout>
<Page>
<Content>
<Input />
<Map />
</Content>
</Page>
<Button />
</Layout>
The Map component should only be rendered once, as there is an animation that is triggered on render. That means that Content, Page and Layout should not re-render at all.
The Button inside Layout should be disabled when the Input is empty. The value of the Input is not controlled by Content, as a state change would cause a re-render of the Map.
I've tried a few different things (using refs, useImperativeHandle, etc) but none of the solutions feel very clean to me. What's the best way to go about connecting the state of the Input to the state of the Button, without changing the state of Layout, Page or Content? Keep in mind that this is a fairly small project and the codebase uses "modern" React practices (e.g. hooks), and doesn't have global state management like Redux, MobX, etc.
Here is an example (click here to play with it) that avoids re-render of Map. However, it re-renders other components because I pass children around. But if map is the heaviest, that should do the trick. To avoid rendering of other components you need to get rid of children prop but that most probably means you will need redux. You can also try to use context but I never worked with it so idk how it would affect rendering in general
import React, { useState, useRef, memo } from "react";
import "./styles.css";
const GenericComponent = memo(
({ name = "GenericComponent", className, children }) => {
const counter = useRef(0);
counter.current += 1;
return (
<div className={"GenericComponent " + className}>
<div className="Counter">
{name} rendered {counter.current} times
</div>
{children}
</div>
);
}
);
const Layout = memo(({ children }) => {
return (
<GenericComponent name="Layout" className="Layout">
{children}
</GenericComponent>
);
});
const Page = memo(({ children }) => {
return (
<GenericComponent name="Page" className="Page">
{children}
</GenericComponent>
);
});
const Content = memo(({ children }) => {
return (
<GenericComponent name="Content" className="Content">
{children}
</GenericComponent>
);
});
const Map = memo(({ children }) => {
return (
<GenericComponent name="Map" className="Map">
{children}
</GenericComponent>
);
});
const Input = ({ value, setValue }) => {
const onChange = ({ target: { value } }) => {
setValue(value);
};
return (
<input
type="text"
value={typeof value === "string" ? value : ""}
onChange={onChange}
/>
);
};
const Button = ({ disabled = false }) => {
return (
<button type="button" disabled={disabled}>
Button
</button>
);
};
export default function App() {
const [value, setValue] = useState("");
return (
<div className="App">
<h1>SO Q#60060672</h1>
<Layout>
<Page>
<Content>
<Input value={value} setValue={setValue} />
<Map />
</Content>
</Page>
<Button disabled={value === ""} />
</Layout>
</div>
);
}
Update
Below is version with context that does not re-render components except input and button:
import React, { useState, useRef, memo, useContext } from "react";
import "./styles.css";
const ValueContext = React.createContext({
value: "",
setValue: () => {}
});
const Layout = memo(() => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Layout rendered {counter.current} times</div>
<Page />
<Button />
</div>
);
});
const Page = memo(() => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Page rendered {counter.current} times</div>
<Content />
</div>
);
});
const Content = memo(() => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Content rendered {counter.current} times</div>
<Input />
<Map />
</div>
);
});
const Map = memo(() => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Map rendered {counter.current} times</div>
</div>
);
});
const Input = () => {
const { value, setValue } = useContext(ValueContext);
const onChange = ({ target: { value } }) => {
setValue(value);
};
return (
<input
type="text"
value={typeof value === "string" ? value : ""}
onChange={onChange}
/>
);
};
const Button = () => {
const { value } = useContext(ValueContext);
return (
<button type="button" disabled={value === ""}>
Button
</button>
);
};
export default function App() {
const [value, setValue] = useState("");
return (
<div className="App">
<h1>SO Q#60060672, method 2</h1>
<p>
Type something into input below to see how rendering counters{" "}
<s>update</s> stay the same
</p>
<ValueContext.Provider value={{ value, setValue }}>
<Layout />
</ValueContext.Provider>
</div>
);
}
Solutions rely on using memo to avoid rendering when parent re-renders and minimizing amount of properties passed to components. Ref's are used only for render counters
I have a sure way to solve it, but a little more complicated.
Use createContext and useContext to transfer data from layout to input. This way you can use a global state without using Redux. (redux also uses context by the way to distribute its data). Using context you can prevent property change in all the component between Layout and Imput.
I have a second easier option, but I'm not sure it works in this case. You can wrap Map to React.memo to prevent render if its property is not changed. It's quick to try and it may work.
UPDATE
I tried out React.memo on Map component. I modified Gennady's example. And it works just fine without context. You just pass the value and setValue to all component down the chain. You can pass all property easy like: <Content {...props} /> This is the easiest solution.
import React, { useState, useRef, memo } from "react";
import "./styles.css";
const Layout = props => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Layout rendered {counter.current} times</div>
<Page {...props} />
<Button {...props} />
</div>
);
};
const Page = props => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Page rendered {counter.current} times</div>
<Content {...props} />
</div>
);
};
const Content = props => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Content rendered {counter.current} times</div>
<Input {...props} />
<Map />
</div>
);
};
const Map = memo(() => {
const counter = useRef(0);
counter.current += 1;
return (
<div className="GenericComponent">
<div className="Counter">Map rendered {counter.current} times</div>
</div>
);
});
const Input = ({ value, setValue }) => {
const counter = useRef(0);
counter.current += 1;
const onChange = ({ target: { value } }) => {
setValue(value);
};
return (
<>
Input rendedred {counter.current} times{" "}
<input
type="text"
value={typeof value === "string" ? value : ""}
onChange={onChange}
/>
</>
);
};
const Button = ({ value }) => {
const counter = useRef(0);
counter.current += 1;
return (
<button type="button" disabled={value === ""}>
Button (rendered {counter.current} times)
</button>
);
};
export default function App() {
const [value, setValue] = useState("");
return (
<div className="App">
<h1>SO Q#60060672, method 2</h1>
<p>
Type something into input below to see how rendering counters{" "}
<s>update</s> stay the same, except for input and button
</p>
<Layout value={value} setValue={setValue} />
</div>
);
}
https://codesandbox.io/s/weathered-wind-wif8b

How to pass a react component as a variable, to child component?

When I have defined a component in a variable, and I am trying to pass it to a component as a children prop, Objects are not valid as a React child error is shown.
What is a correct way to do this?
function AnotherComponent(){
return "Another";
}
function ChildComponent(props) {
const { children, value, index, ...other } = props;
console.log(children);
return (
<Typography
component="div"
role="tabpanel"
hidden={value !== index}
id={`full-width-tabpanel-${index}`}
aria-labelledby={`full-width-tab-${index}`}
{...other}
>
<Box p={3}>{children}</Box>
</Typography>
);
}
function MainComponent(){
const tabItems = [
{ "component": AnotherComponent}
];
const [value, setValue] = React.useState(0);
return (
<>
{tabItems.map((tabItem,index) => (
<ChildComponent value={value} index={tabItem.index}>
{tabItem.component}
</ChildComponent>
))}
</>
)
}
tabItem.component is just an object. This should work :
{tabItems.map((tabItem, index) => {
const TheComponent = tabItem.component;
return (
<TabPanel value={value} index={tabItem.index}>
<TheComponent />
</TabPanel>
);
})}
The problem is the way you initialise the array is really just assigning a function into it. Exactly as error says - you cant render a function. You have to wrap that function into JSX syntax to do the whole React.createChild thingy.
So just change this line
const tabItems = [
{ "component": AnotherComponent}
];
to this:
const tabItems = [
{ "component": <AnotherComponent />}
];
and it will work like a charm. :)

React Hook : Send data from child to parent component

I'm looking for the easiest solution to pass data from a child component to his parent.
I've heard about using Context, pass trough properties or update props, but I don't know which one is the best solution.
I'm building an admin interface, with a PageComponent that contains a ChildComponent with a table where I can select multiple line. I want to send to my parent PageComponent the number of line I've selected in my ChildComponent.
Something like that :
PageComponent :
<div className="App">
<EnhancedTable />
<h2>count 0</h2>
(count should be updated from child)
</div>
ChildComponent :
const EnhancedTable = () => {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Click me {count}
</button>
)
};
I'm sure it's a pretty simple thing to do, I don't want to use redux for that.
A common technique for these situations is to lift the state up to the first common ancestor of all the components that needs to use the state (i.e. the PageComponent in this case) and pass down the state and state-altering functions to the child components as props.
Example
const { useState } = React;
function PageComponent() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1)
}
return (
<div className="App">
<ChildComponent onClick={increment} count={count} />
<h2>count {count}</h2>
(count should be updated from child)
</div>
);
}
const ChildComponent = ({ onClick, count }) => {
return (
<button onClick={onClick}>
Click me {count}
</button>
)
};
ReactDOM.render(<PageComponent />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
You can create a method in your parent component, pass it to child component and call it from props every time child's state changes, keeping the state in child component.
const EnhancedTable = ({ parentCallback }) => {
const [count, setCount] = useState(0);
return (
<button onClick={() => {
const newValue = count + 1;
setCount(newValue);
parentCallback(newValue);
}}>
Click me {count}
</button>
)
};
class PageComponent extends React.Component {
callback = (count) => {
// do something with value in parent component, like save to state
}
render() {
return (
<div className="App">
<EnhancedTable parentCallback={this.callback} />
<h2>count 0</h2>
(count should be updated from child)
</div>
)
}
}
To make things super simple you can actually share state setters to children and now they have the access to set the state of its parent.
example:
Assume there are 4 components as below,
function App() {
return (
<div className="App">
<GrandParent />
</div>
);
}
const GrandParent = () => {
const [name, setName] = useState("i'm Grand Parent");
return (
<>
<div>{name}</div>
<Parent setName={setName} />
</>
);
};
const Parent = params => {
return (
<>
<button onClick={() => params.setName("i'm from Parent")}>
from Parent
</button>
<Child setName={params.setName} />
</>
);
};
const Child = params => {
return (
<>
<button onClick={() => params.setName("i'm from Child")}>
from Child
</button>
</>
);
};
so grandparent component has the actual state and by sharing the setter method (setName) to parent and child, they get the access to change the state of the grandparent.
you can find the working code in below sandbox,
https://codesandbox.io/embed/async-fire-kl197
IF we Have Parent Class Component and Child function component this is how we going to access child component useStates hooks value :--
class parent extends Component() {
constructor(props){
super(props)
this.ChildComponentRef = React.createRef()
}
render(){
console.log(' check child stateValue: ',
this.ChildComponentRef.current.info);
return (<> <ChildComponent ref={this.ChildComponentRef} /> </>)
}
}
Child Component we would create using
React.forwardRef((props, ref) => (<></>))
. and
useImperativeHandle(ref, createHandle, [deps])
to customizes the instance value that is exposed to parent components
const childComponent = React.forwardRef((props, ref) => {
const [info, setInfo] = useState("")
useEffect(() => {
axios.get("someUrl").then((data)=>setInfo(data))
})
useImperativeHandle(ref, () => {
return {
info: info
}
})
return (<> <h2> Child Component <h2> </>)
})
I had to do this in type script. The object-oriented aspect would need the dev to add this callback method as a field in the interface after inheriting from parent and the type of this prop would be Function. I found this cool!
Here's an another example of how we can pass state directly to the parent.
I modified a component example from react-select library which is a CreatableSelect component. The component was originally developed as class based component, I turned it into a functional component and changed state manipulation algorithm.
import React, {KeyboardEventHandler} from 'react';
import CreatableSelect from 'react-select/creatable';
import { ActionMeta, OnChangeValue } from 'react-select';
const MultiSelectTextInput = (props) => {
const components = {
DropdownIndicator: null,
};
interface Option {
readonly label: string;
readonly value: string;
}
const createOption = (label: string) => ({
label,
value: label,
});
const handleChange = (value: OnChangeValue<Option, true>, actionMeta: ActionMeta<Option>) => {
console.group('Value Changed');
console.log(value);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
props.setValue(value);
};
const handleInputChange = (inputValue: string) => {
props.setInputValue(inputValue);
};
const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
if (!props.inputValue) return;
switch (event.key) {
case 'Enter':
case 'Tab':
console.group('Value Added');
console.log(props.value);
console.groupEnd();
props.setInputValue('');
props.setValue([...props.value, createOption(props.inputValue)])
event.preventDefault();
}
};
return (
<CreatableSelect
id={props.id}
instanceId={props.id}
className="w-100"
components={components}
inputValue={props.inputValue}
isClearable
isMulti
menuIsOpen={false}
onChange={handleChange}
onInputChange={handleInputChange}
onKeyDown={handleKeyDown}
placeholder="Type something and press enter..."
value={props.value}
/>
);
};
export default MultiSelectTextInput;
I call it from the pages of my next js project like this
import MultiSelectTextInput from "../components/Form/MultiSelect/MultiSelectTextInput";
const NcciLite = () => {
const [value, setValue] = useState<any>([]);
const [inputValue, setInputValue] = useState<any>('');
return (
<React.Fragment>
....
<div className="d-inline-flex col-md-9">
<MultiSelectTextInput
id="codes"
value={value}
setValue={setValue}
inputValue={inputValue}
setInputValue={setInputValue}
/>
</div>
...
</React.Fragment>
);
};
As seen, the component modifies the page's (parent page's) state in which it is called.
I've had to deal with a similar issue, and found another approach, using an object to reference the states between different functions, and in the same file.
import React, { useState } from "react";
let myState = {};
const GrandParent = () => {
const [name, setName] = useState("i'm Grand Parent");
myState.name=name;
myState.setName=setName;
return (
<>
<div>{name}</div>
<Parent />
</>
);
};
export default GrandParent;
const Parent = () => {
return (
<>
<button onClick={() => myState.setName("i'm from Parent")}>
from Parent
</button>
<Child />
</>
);
};
const Child = () => {
return (
<>
<button onClick={() => myState.setName("i'm from Child")}>
from Child
</button>
</>
);
};

Resources