Is it possible I can dynamic import based on the props from Parent in React?
For my code:
Parent
<Parent>
<Child icon="svg1" />
<Child icon="svg2" />
<Child icon="svg3" />
</Parent>
Child
import svg1 from './svg1.js'
import svg2 from './svg2.js'
import svg3 from './svg3.js'
switch (props.icon)
{
case 'svg1':
output = <svg1/>
break
case 'svg2':
ouput = <svg2/>
break
default:
ouput = <svg3/>
}
return (
<div>
{output}
</div>
)
How can I use a dynamic icon value to import svg element based on the icon value from parent rather than swtich?
If you want to avoid doing a switch, you could build an object with your imports:
const icons = {
svg1,
svg2,
svg3,
};
const Child = (props) => {
const Component = icons[props.icon];
return <Component />;
};
You could try using the image tag, like this;
import svg1 from './svg1.js'
import svg2 from './svg2.js'
import svg3 from './svg3.js'
<Parent>
<Child icon={svg1} />
<Child icon={svg2} />
<Child icon={svg3} />
</Parent>
Child
return (
<div>
<img src={output} />
</div>
)
Based on this one - https://sung.codes/blog/2017/12/03/loading-react-components-dynamically-demand/
I finally get the solution:
const { icon } = props
const [components, setComponents] = useState([])
const addComponent = async (icon) => {
import(`./${icon}.js`)
.then((component) => {
setComponents(components.concat(component.default))
})
.catch((error) => {
console.error(`"${icon}" not yet supported`)
})
}
const getElement = async (icon) => {
await addComponent(icon)
}
useEffect(() => {
console.log("icon", icon)
getElement(icon)
}, [])
const componentsElements = components.map((Component) => <Component />)
...
return <div>{componentsElements}</div>
Related
I have two components, the parent and child. Currently I have these codes below. But unfortunately it returns an error:
TypeError: Cannot read property 'click' of null
For some reasons I want when button is click the Item component also will be click. But these codes below produces an error above. Anyone does know how to achieve it?
import React, { useRef } from 'react';
const App = (props) => {
const itemRef = useRef(null);
return (
<div>
{dynamicBoolean ? (
<button onClick={() => itemRef.current.click()}>
click item
</button>
) : (
//more codes here
<Item ref={itemRef} />
)}
</div>
);
};
export default App;
Child component would look like below (demonstration purposes, the code is very lengthly)
import React from 'react';
const Item = (props) => {
return (
<div>
//some design here
</div>
);
};
export default Item;
You need useRef and you have to forward this ref to the Item component.
import React, { forwardRef, useRef } from 'react';
const Item = forwardRef((props, ref) => {
return <li {...props}
onClick={() => alert('clicked on Item')}
ref={ref} >MyItem</li>
})
const App = (props) => {
const itemRef = useRef(null);
return (
<div>
<button onClick={() => itemRef.current.click()}>
click item
</button>
<Item ref={itemRef} />
</div>
);
};
export default App;
import React, { createRef } from "react";
const Hello = (props) => {
const itemRef = createRef();
const hello = () => {
itemRef.current.click();
};
return (
<div>
<button onClick={() => hello()}>click item</button>
<Item ref={itemRef} />
</div>
);
};
const Item = React.forwardRef((props, ref) => {
const myClick = () => {
console.log("this is clicked");
};
return (
<button ref={ref} className="FancyButton" onClick={myClick}>
{props.children}
</button>
);
});
export default Hello;
This question already has an answer here:
List elements not rendering in React [duplicate]
(1 answer)
Closed 24 days ago.
I am going through a react course and currently learning react's lifecycle method. So far, I have been able to call the API using componentDidMount and have set the state. However, I can't seem to get the card components to show the images in the cardlist div. I'm sure I've done it correctly (looping through the state and creating a Card component with the props).
import react, {Component} from 'react';
import axios from 'axios';
import Card from './Card';
const api = ' https://deckofcardsapi.com/api/deck/';
class CardList extends Component {
state = {
deck: '',
drawn: []
}
componentDidMount = async() => {
let response = await axios.get(`${api}new/shuffle`);
this.setState({ deck: response.data })
}
getCards = async() => {
const deck_id = this.state.deck.deck_id;
let response = await axios.get(`${api}${deck_id}/draw/`);
let card = response.data.cards[0];
this.setState(st => ({
drawn: [
...st.drawn, {
id: card.code,
image: card.image,
name: `${card.value} of ${card.suit}`
}
]
}))
}
render(){
const cards = this.state.drawn.map(c => {
<Card image={c.image} key={c.id} name={c.name} />
})
return (
<div className="CardList">
<button onClick={this.getCards}>Get Cards</button>
{cards}
</div>
)
}
}
export default CardList;
import react, {Component} from 'react';
class Card extends Component {
render(){
return (
<img src={this.props.image} alt={this.props.name} />
)
}
}
export default Card;
import CardList from './CardList';
function App() {
return (
<div className="App">
<CardList />
</div>
);
}
export default App;
Your map function:
const cards = this.state.drawn.map(c => {
<Card image={c.image} key={c.id} name={c.name} />
})
does not return anything. So the result of this code is an array of undefined.
You have two options:
Add return:
const cards = this.state.drawn.map(c => {
return <Card image={c.image} key={c.id} name={c.name} />
})
Wrap in (), not {}:
const cards = this.state.drawn.map(c => (
<Card image={c.image} key={c.id} name={c.name} />
))
You should return the card component inside the map
const cards = this.state.drawn.map(c => {
return <Card image={c.image} key={c.id} name={c.name} />
})
I have this structure
component 1
import React, { useState } from 'react'
export default function Component1() {
return (
<div>
<button onClick={handleChange}></button>
</div>
)
}
component 2
import React, { useState } from 'react'
export default function Component2() {
return (
<div>
<button onClick={handleChange}></button>
</div>
)
}
and the parent
import React from 'react'
export default function Parent() {
return (
<div>
<Component1 />
<Component2 />
</div>
)
}
The question is, how can I toggle visibility between the two, without having a button in the parent. Just the buttons inside each component. - The Component1 should be visible by default and when you press the button in Component1 it will hide it and show Component2 and vice-versa.
I've tried using useState hook on the Component1 button, but I'm not sure how to export the state and add it to the parent component.
const [showMini, setShowMini] = useState(false);
const handleChange = () => {
setShowMini(true);
}
Is this possible? or it's possible just with a button in the parent that control the two?
Thanks
Try this:
import React from 'react'
export default function Parent() {
const[show,setShow]=useState(false);
const handleChange=()=>{
setShow(!show);
}
return (
<div>
{show ? <Component2 handleChange={handleChange}/> : <Component1 handleChange={handleChange}/>}
</div>
)
}
and inside Component1 have this:
import React, { useState } from 'react'
export default function Component1({handleChange}) {
return (
<div>
<button onClick={handleChange}></button>
</div>
)
}
Similarly do it for Component2
You can do with state value and pass handleChange function ad props in the child component and in click on the button in child component call handleChange method under parent component and show hide based on state value.
import React from 'react'
const [showChild, setshowChild] = useState(false);
const handleChange = () => {
setshowChild(!showChild);
}
export default function Parent() {
return (
<div>
{showChild ? <Component2 handleChange = {handleChange}/> : <Component1 handleChange= {handleChange} />}
</div>
)
}
You can manage the state in the parent and pass down a handler to the children
import React, { useState } from 'react'
const [currentView, setCurrentView] = useState('component1')
const changeCurrentView = (view) => setCurrentView(view)
const renderViews = () => {
switch(currentView) {
case 'component1':
return <Component1 changeCurrentView={changeCurrentView} />
case 'component2':
return <Component2 changeCurrentView={changeCurrentView} />
default:
return <Component1 changeCurrentView={changeCurrentView} />
}
}
export default function Parent() {
return (
<div>
{renderViews()}
</div>
)
}
Other components
import React from 'react'
export default function Component1({ changeCurrentView }) {
return (
<div>
<button onClick={() => changeCurrentView('component1')}></button>
</div>
)
}
export default function Component2({ changeCurrentView }) {
return (
<div>
<button onClick={() => changeCurrentView('component2')}></button>
</div>
)
}
Your parent component should keep track of the state:
import React, {useState} from 'react'
export default function Parent() {
const [showChild, setShowChild] = useState(1);
const showNextChild = () => {
setShowChild( showChild === 1 ? 2 : 1 ); // set to 2 if already 1, else to 1
}
return (
<div>
{ showChild === 1 && <Component1 handleChange={showNextChild} /> }
{ showChild === 2 && <Component2 handleChange={showNextChild} /> }
</div>
)
}
A few notes:
Your components are identical, so the duplication is unnecessary, but I assume the example is just contrived.
This assumes toggling 2 components back and forth. If you have more than 2 components you are "looping" through, you can instead increment the previous showChild state and then reset it to 0 if higher than the # of components you have.
The syntax you see, showChild === 1 && <Component1 ... uses the behavior of the && operator which actually returns the 2nd item it is evaluating if both are true. In other words, const isTrue = foo && bar; sets isTrue to bar, not true as you might expect. (You know, however, that bar is "truthy" in this case, so isTrue still works in future if statements and such.) The component is always truthy, so the effect is that the component is returned if the first part is true, otherwise it is not. It's a good trick for conditionally showing components.
Try this. You can send information from child to parent with functions passed as a prop.
Parent Component:
const Parent = () => {
const [show, setShow] = useState(true);
const toggleVisibility = () => {
setShow(!show);
};
return (
<div>
{show ? (
<Child1 toggle={toggleVisibility}></Child1>
) : (
<Child2 toggle={toggleVisibility}></Child2>
)}
</div>
);
};
Child 1
const Child1 = (props) => {
const { toggle } = props;
return (
<div style={{ width: '100px', height: '100px' }}>
<button onClick={toggle}>Child 1's button</button>
</div>
);
};
Child 2
const Child2 = (props) => {
const { toggle } = props;
return (
<div style={{ width: '100px', height: '100px' }}>
<button onClick={toggle}>Child 2's button</button>
</div>
);
};
how would I get the state from the child so that the parent recognise the state from that child has changed?
const grandParent = () => (
<parent>
<child/>
</parent>
);
const child = () => {
const [isOpen, setOpen] = useState(false)
return (
<button onClick={()=>setOpen(!isOpen)}>Open</button>
)};
const grandParent = () => {
const [ isOpen, setOpen ] = useState(false)
return (
<parent>
<child onHandlerClick={ () => setOpen(!isOpen) }/>
</parent>
);
};
const child = (onHandlerClick) => {
// Note I removed the local state. If you need the state of the parent in the child you can pass it as props.
return (
<button onClick={ () => onHandlerClick() }>Open</button>
);
};
When you need to keep the state in the parent and modify it inside the children, no matter child state. You pass a handler in props from the parent where it's defined to modify the state. The child execute this handler.
This pattern is called state hoisting.
I think I would do something like that:
function GrandParent(){
return <Parent />
}
function Parent() {
const [isOpen, setOpen] = useState(false);
const handleToggle = useCallback(() => {
setOpen(!isOpen);
}, [isOpen, setOpen]);
return <Child handleToggle={handleToggle} />;
}
function Child(props) {
return <button onClick={() => props.handleToggle()}>Open</button>;
}
You can do the following using functional component. Write the Child component as below:
import React, {useEffect, useState} from 'react';
function Child(props) {
const {setStatus} = props;
const [isOpen, setOpen] = useState(false);
function clickHandler() {
setOpen(!isOpen);
setStatus(`changes is ${!isOpen}`);
}
return (
<div>
<button onClick={clickHandler}>Open</button>
</div>
);
}
export default Child;
Write the GrandParent component as below:
import React, {useEffect, useState} from 'react';
import Child from "./Child";
function GrandParent(props) {
function setStatus(status) {
console.log(status);
}
return (
<div>
<Child setStatus={setStatus}></Child>
</div>
);
}
export default GrandParent;
Use GrandParent component in App.js as below:
import React from "react";
import GrandParent from "./GrandParent";
class App extends React.Component {
render() {
return (
<GrandParent/>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
export default App;
You can add props to child and call onChange each time the state is changed
const grandParent = () => (
function handleChange() {}
<parent>
<child onChange={handleChange} />
</parent>
);
const child = (props) => {
const [isOpen, setOpen] = useState(false);
function onChange() {
setOpen(prevOpen => {
props.onChange(!prevOpen);
return !prevOpen;
});
}
return (
<button onClick={()=>setOpen(!isOpen)}>Open</button>
)};
You can do something like this:
const grandParent = () => {
const [isOpen, setOpen] = useState(false)
return (
<parent isOpen>
<child isOpen onChangeState={() => setOpen(!isOpen)} />
</parent>
)
}
const child = (props) => {
return (
<button
onClick={() => {
props.onChangeState()
}}>
Open
</button>
)
}
Explanation:
You manage the state in the grandParent component and passing it in the parent component (and also at the child if you need it).
The child has a prop which is called when the button is clicked and leads to the update of the grandParent state
I have a top level context Provider, followed by a Parent class component follow by a functional stateless Child.
I can update the my context value from the Child, but not from the parent, even though the value updates in the parent.
How can I update and share state between both components using context?
import React from "react";
import ReactDOM from "react-dom";
const Context = React.createContext();
const Provider = ({ children }) => {
const [value, setValue] = React.useState(0);
return (
<Context.Provider value={{ value, setValue }}>{children}</Context.Provider>
);
};
const Child = () => {
const { value, setValue } = React.useContext(Context);
return <div onClick={() => setValue(value + 1)}>Plus plus!!</div>;
};
class Parent extends React.Component {
render() {
const { value, setValue } = this.context;
return (
<div>
<div onPress={() => setValue(value - 1)}>MINUS MINUS!</div>
<div>{this.props.children}</div>
<h1>{value}</h1>
</div>
);
}
}
Parent.contextType = Context;
function App() {
return (
<Provider>
<Parent>
<Child />
</Parent>
</Provider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
https://codesandbox.io/s/thirsty-oskar-ocmxr
Change the "onPress" to "onClick" will work. I have tested it.