I want to write a program in react jsx when mouseover on an element suppose <li>
<li><a>Pakistan cricket won the match</a></li>
<li><a>We should exercise every day</a></li>
and add these childs elements to coressponding <li>
element
<img src='...' />
<p>details of header</p>
<button>add to favorite</button>
When mouseout from an <li>
element the coressponding childs should be removed
Note:when mouseover, the childs elements should be workable
CodePudding user response:
So basically you need to have onm ouseEnter and onm ouseLeave on parent elements and make a state that holds whether to show the additional data here is a simple example
import "./styles.css";
import {useState} from 'react'
function Children(){
return (
<>
<img src='https://picsum.photos/200/300' />
<p>details of header</p>
<button>add to favorite</button>
</>
)
}
function Parent() {
const [isMouseOver,setIsMouseOver] = useState(false)
const handleEnter = () => {
setIsMouseOver(true)
}
const handleLeave = () => {
setIsMouseOver(false)
}
return(
<div onMouseEnter={handleEnter} onMouseLeave={handleLeave}>
<h1>Hover me</h1>
{isMouseOver ?
<>
<Children />
</>:
null
}
</div>
)
}
export default function App() {
return (
<div className="App">
<Parent />
</div>
);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Similarly, you would change the Parent component to your li and the additional data that should be visible to Children Component.
Note that in this example h1 is a block component so you should leave the whole block to make the data disappear
demo at : https://codesandbox.io/s/silly-dewdney-d8btf?file=/src/App.js:0-738
CodePudding user response:
You can add some class and in its respective CSS, handle the mouseover (:hover
).
App.js
import "./styles.css";
function ListItem({i})
{
return (
<li className="listitem">
<a href="stackoverflow.com">Link{i}</a>
<img className="hideele" src="" alt={i} />
<p className="hideele">Para{i}</p>
<button className="hideele">Button{i}</button>
</li>
);
}
export default function App() {
return (
<div className="App">
<ul>
<ListItem i={1} />
<ListItem i={2} />
<ListItem i={3} />
</ul>
</div>
);
}
Index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
rootElement
);
CSS:
.App {
font-family: sans-serif;
}
.listitem:hover .hideele {
display: block;
}
.hideele {
display: none;
}