I have a Nav component:
class SomeClass extends React.Component{
showItem = () =>{
console.log("itemShown");
return(
<Item/>
);
}
render(){
return(
<div onClick={() => this.showItem()} >
ABC
</div>
);
}
export default Nav;
I am calling it in App.js:
function App() {
return (
<div className="app">
<SomeClass />
</div>
);
}
export default App;
How to have the Item component in the showItem method in SomeClass, to be shown in the App functional component.
In App.js I tried:
<div className="app">
<SomeClass showItem={showItem} />
</div>
However, it did not work.
What is the best approach to this ?
You can manage a state inside your SomeClass component as follows. Then you can toggle it whenever you need to show or un-show the Item component.
class SomeClass extends React.Component {
constructor(props) {
super(props);
this.state = {
isShowItem: false,
};
this.showItem = this.showItem.bind(this);
}
showItem = () => {
this.setState(!this.state.isShowItem);
};
render() {
return (
<>
<div onClick={this.showItem}>ABC</div>
{this.state.isShowItem && <Item />}
</>
);
}
}
export default SomeClass;
These days people don't tend to use react classes, they use functional components. Here's how you do it with functional components.
State Hook:
toggleShowItem swaps the showItem state between true and false when ever the SomeClass (which isn't a class anymore but that's what you have named yours) component's onClick is fired.
Conditional Rendering:
The ShowItem is rendered whenever the state hook's value is true.
export default function App() {
const [showItem, setShowItem] = useState(false);
const toggleShowItem = () => {
setShowItem(!showItem);
}
return (
<div className="App">
<SomeClass toggleShowItem={toggleShowItem}>
{showItem && <ShowItem />}
</SomeClass>
</div>
);
}
export default function SomeClass({toggleShowItem}) {
return <div onClick={toggleShowItem}>ABC</div>;
}
The better way to show the Item component is to use React State and React Props. Please read this docs since it will help you greatly on react development.
Option 1:
there will be a state in the App component for showItem. Then you pass the showItem as props in the SomeClass component.
Option 2:
the state for showItem is in the SomeClass Component, then upon clicking the toggle, the state will be updated.