React js : Change img on Div whith onMouseOver - hover

I need your help :) (but first, sorry for my aproximate english ...).
I would like to change the 'img src' in the 'div-img' when I pass the mouse over one of the 'a' balise ... I try onMouseOver, but i failled :(
There is an image by 'a' which replaces the one in 'div-img'
EDIT : Okay, here is the almost complete code, to really see the problem :
#observer
export default class Home extends React.Component {
static readonly language = "language";
private static readonly en = "en";
private static readonly fr = "fr";
#observable private static selectLanguage = false;
public render(): ReactElement {
if (Home.selectLanguage) {
return (
<div style={{ height: '100vh', width: '100vw', overflow: 'hidden'}}>
<MyHead />
<body style={{backgroundColor: 'rgb(51, 63, 72)'}}>
<div style={{
maxWidth: '1150px',
height: '300px',
margin: 'auto',
}}>
<div style={{ display: 'flex', maxWidth: '450px'}}>
<img style={{
maxWidth: '100%',
margin: 'auto'
}}
src='/images/***.png'/>
</div>
</div>
<div style={{
display: 'flex',
flexWrap: 'wrap',
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
zIndex: 1,
}}>
<a href="/fr/" onClick={_ => { localStorage.setItem(Home.language, Home.fr); }} >
<span className= 'shadow'>
<div style={{ margin: '0 15px', padding: '75px', backgroundColor: 'rgb(175, 39, 47)', clipPath: 'polygon(0 0, 100% 8%, 100% 92%, 0 100%)'}} >
<h2>Français</h2>
</div>
</span>
</a>
<a href="/en/" onClick={_ => {localStorage.setItem(Home.language, Home.en);}}>
<span className= 'shadow'>
<div style={{ margin: '0 15px', padding: '75px', backgroundColor: 'rgb(175, 39, 47)', clipPath: 'polygon(0 8%, 100% 0, 100% 100%, 0 92%)'}}>
<h2>English</h2>
</div>
</span>
</a>
</div>
<main style={{filter: 'blur(4px)'}}>
<component1 />
<component2 />
</main>
</body>
</div>
)
}
Thank you very much in advance !

I have made a few changes to your code, first of all, I am using mouseOnEnter instead of mouseOnHover and I have also added mouseOnLeave to reset the image(because in the question you have mentioned that you want to change the image when you pass over the (Link) tag.
My solution uses the useState react hook, onMouseEnter for the div sets a random image using
https://i.picsum.photos/id/${Math.floor(Math.random() * 1084)}/50/50.jpg
https://i.picsum.photos/id/{image_id}/{width}/{height}.jpg
https://i.picsum.photos/id/50/50/50.jpg
OnMouseEnter the state is updated to the images src / location and is reset to '' onMouseLeave. Also, I have added
style={{ width: '50px', height: '50px' }}
to the div so as to keep the divs from moving around when hovering over links in the sample code. 50px is also the height of the image.
import React, { useState } from 'react'
const testCode = () => {
const [image, setImage] = useState('')
return (
<>
<div className="div-img" style={{ width: '50px', height: '50px' }}>
<img src={image} />
</div>
<div>
<a href="/fr/" onMouseEnter={() => setImage(`https://i.picsum.photos/id/${Math.floor(Math.random() * 1084)}/50/50.jpg`)} onMouseLeave={() => setImage('')}>
<span className="shadow">
<div>
<h2>Lorem</h2>
</div>
</span>
</a>
<a href="/en/" onMouseEnter={() => setImage(`https://i.picsum.photos/id/${Math.floor(Math.random() * 1084)}/50/50.jpg`)} onMouseLeave={() => setImage('')}>
<span className="shadow">
<div>
<h2>Lorem</h2>
</div>
</span>
</a>
</div>
</>
)
}
export default testCode
Updated: Using React Class
import React, { Component } from 'react'
class sampleCode extends Component {
constructor(props) {
super(props);
this.state = { image: '' };
}
setImage = (imagePath) => {
this.setState({ image : imagePath })
}
render() {
return (
<>
<div className="div-img" style={{ width: '50px', height: '50px' }}>
<img src={this.state.image}/>
</div>
<div>
<a href="/fr/"
onMouseEnter={() => this.setImage(`https://i.picsum.photos/id/${Math.floor(Math.random() * 1084)}/50/50.jpg`)}
onMouseLeave={() => this.setImage('')}>
<span className="shadow">
<div>
<h2>Lorem</h2>
</div>
</span>
</a>
<a href="/en/"
onMouseEnter={() => this.setImage(`https://i.picsum.photos/id/${Math.floor(Math.random() * 1084)}/50/50.jpg`)}
onMouseLeave={() => this.setImage('')}>
<span className="shadow">
<div>
<h2>Lorem</h2>
</div>
</span>
</a>
</div>
</>
)
}
}
export default sampleCode
Hope this helps :)

Related

A dropdown field make the conatiner "scrollable"

A dropdown field make the conatiner "scrollable" and cuts off the dropdown selections, selector must float above the container.
for other reasons I cannot change the overflow: auto in the outer container
Thanks for helping me
import "./styles.css";
import { useState, useRef, useEffect } from "react";
import styled from "styled-components";
export default function App() {
const ref = useRef(null);
const difference = useRef();
const [expanded, setExpanded] = useState(false);
useEffect(() => {
const height = ref.current.offsetHeight;
difference.current = height;
console.log(height);
}, [expanded]);
return (
<div
style={{ height: "60px", backgroundColor: "lightblue", overflow: "auto" }}
>
<div ref={ref} style={{ position: "relative" }}>
<span onClick={() => setExpanded((previousState) => !previousState)}>
See Options
</span>
{expanded && (
<div>
<div>
{["Option 1", "Option 2", "Option 3"].map((option, i) => (
<div
style={{
border: "1px solid green",
width: "60px"
}}
key={i}
onClick={(e) => {
e.stopPropagation();
console.log(option);
}}
>
{option}
</div>
))}
</div>
</div>
)}
</div>
</div>
);
}
Make your dropdown container have an absolute position, relative to the container it's in.
Absolute position means your parent container will ignore the width and height of the dropdown, which means the dropdown will not affect the height of the parent container.

Problem with Sticky Header, content below it not showing ( React, Ant Design )

Header Component
<Header
className="site-layout-header"
style={{
position: "sticky",
top: 0,
zIndex: 999,
width: "100%",
padding: 30,
backgroundColor: "#fff",
...style,
}}
>
{children}
</Header>
Below this I am using header component like this
const IncidentProfile = (props: any) => {
const { record } = props.location?.state || {};
return (
<>
<Header record={record} />
<Content
className="site-layout-background"
style={{
padding: 24,
}}
>
<h1>Incident Profile Page {record?.name}</h1>
</Content>
</>
);
};
When the Header component height increases dynamically, it scrolls and stay sticky but the content below it is not showing.
Can anyone help ?

Trying to place an image in a fixed positon. Why the image is misplaced until I do a page refresh?

Newbie here.
I just started playing around with ReactJS on codesandbox.
I want to keep an image element (the green arrow) in a specific position over the gauge element. I tried it the simplest way I could think of, and it kinda suits what I need, but...
When I open the page, the image is misplaced, but if I do a page refresh, the image will be exactly where I want it... why?! What can be the reason and any idea of how to solve it?
Perhaps, can you tell me any other way of positioning an image in a specific place inside the div?
Here's the link: https://codesandbox.io/embed/gauge-ship-engine-1-h2nhx?fontsize=14&hidenavigation=1&theme=dark&codemirror=1
Here's the code:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import ReactSpeedometer from "react-d3-speedometer";
import "bootstrap/dist/css/bootstrap.min.css";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import arrow from "./greenarrow.png";
class Gauge extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
this.handleGaugeValueChange = this.handleGaugeValueChange.bind(this);
}
handleGaugeValueChange(e) {
console.log(1);
this.setState({
value: e.target.value
});
}
render() {
return (
<div className="center">
<h1 className="title">Ship Engine 1</h1>
<Container className="p-3">
<Row>
<Col>
<div
className="speedometer"
style={{
width: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<img
src={arrow}
alt="greenarrow"
style={{
position: "absolute",
opacity: 1,
zIndex: "1",
transform: "rotate(-35deg)",
marginLeft: "-65px",
marginTop: "-80px"
}}
/>
<ReactSpeedometer
maxValue={150}
ringWidth={20}
customSegmentStops={[0, 30, 55, 65, 90, 120, 150]}
segmentColors={[
"#FAFAFA",
"#FAFAFA",
"#007fff",
"#FAFAFA",
"#FAFAFA",
"#FAFAFA"
]}
needleHeightRatio={0.72}
valueTextFontSize="19px"
needleTransitionDuration={9000}
needleTransition="easeElastic"
currentValueText="${value} kW"
value={this.state.value}
/>
</div>
<div className="divLabelReq">
<label
className="labelReq"
htmlFor="value"
style={{ color: "#6b6964" }}
>
Requested: 39.7kW
</label>
</div>
</Col>
<Col>
<form className="form-settings" onSubmit={this.handleSubmit}>
<div className="form-row">
<div className="form-group col-md-5">
<label
className="label"
htmlFor="value"
style={{ color: "white" }}
>
Change Gauge Value:{" "}
</label>
<input
type="number"
className="form-control"
name="value"
id="value"
placeholder="0"
onChange={this.handleGaugeValueChange}
value={this.state.keywords}
/>
</div>
</div>
</form>
</Col>
</Row>
</Container>
</div>
);
}
}
export default Gauge;
const rootElement = document.getElementById("root");
ReactDOM.render(<Gauge />, rootElement);
Thanks in advance!
It looks like your green arrow has not a reference. For instance the parent element has not a position declared. Try something like:
<div
className="speedometer"
style={{
width: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center",
position: "relative"
}}
>

how to apply bootstrap active class to an onclick

How do you apply a bootstrap class like nav-link active to a onlick(). I've been having hard time implementing this. I thought it would have just been as simple as.
<a
onClick={() => this.props.onUpdateSelectedProbe(probe)}
className="dropdown-item nav-link active"
>
But this however just makes all list items/anchor tags active.
return (
<div style={{ alignSelf: "center" }}>
<ul className="nav nav-pills">
<li className="nav-item dropdown ">
<div
className="dropdown-menu show"
x-placement="bottom-start"
style={{
position: "relative",
willChange: "transform",
top: "5px",
overflowY: "scroll",
maxHeight: "200px"
}}
>
{this.props.searchState.isActive === false
? probes.map(probe => (
<a
onClick={() => this.props.onUpdateSelectedProbe(probe)}
className="dropdown-item"
>
<div
className="dropdown-divider"
style={{ backgroundColor: "black" }}
></div>
{probe.companyPN}: {probe.description}
</a>
))
: filteredProbes.map(filterprobe => (
<a
onClick={() =>
this.props.onUpdateSelectedProbe(filterprobe)
}
className="dropdown-item"
>
<div className="dropdown-divider"></div>
{filterprobe.companyPN}: {filterprobe.description}
</a>
))}
</div>
</li>
</ul>
</div>
);
This is a basic example of adding items to a list and conditionally showing a "selected" class
.selected {
background: red;
}
function App() {
const [people] = useState([
{ id: 0, name: "Mario" },
{ id: 1, name: "Luigi" },
{ id: 2, name: "Peach" }
]);
const [selected, setSelected] = useState({});
return (
<div>
{people.map(({ id, name }) => (
<div
className={selected[id] ? "selected" : ""}
key={id}
onClick={() => setSelected({ ...selected, [id]: true })}
>
{name}
</div>
))}
</div>
);
}
https://codesandbox.io/s/funny-nobel-e6x6e

React Google Map : a UL of all markers binded in GoogleMap and corresponding info window on click of each li

I did a google map with a list of resellers using "react-google-maps"
The markers properly looping and showing in the map
How can I list the 'Marker'/'Resellers' in the Map into a list(UL) too, Also the list(li) click should pop the info window?
This is the one I used, https://gist.github.com/jwo/43b382fc60eb09d3a415c9953f4057f8
import React, { Component } from "react"
import { compose } from "recompose"
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
InfoWindow, Listing
} from "react-google-maps"
const MapWithAMarker = compose(withScriptjs, withGoogleMap)(props => {
const listStyle = {
width: '250px',
position: "relative"
}
return (
<div style={{ position: "relative" }}>
<GoogleMap defaultZoom={4} defaultCenter={{ lat: 56.263920, lng: 9.501785 }}>
{props.markers.map(marker => {
if (marker.lat != null) {
const onClick = props.onClick.bind(this, marker)
return (
<Marker
key={marker.customerNumber}
onClick={onClick}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.lng) }}
>
{props.selectedMarker === marker &&
<InfoWindow>
<div>
<h1> {marker.name}</h1>
<br />
{marker.address}
<br />
{marker.zipcode} {marker.city}
<br />
Telephone: {marker.phone}
</div>
</InfoWindow>}
{/* List resellers here, so info window can be reused I guess, not sure */}
</Marker>
)
}
})}
</GoogleMap>
</div>
)
})
export default class ResellerGoogleMap extends Component {
constructor(props) {
super(props);
this.state = {
showingInfoWindow: false,
selectedMarker: {},
selectedPlace: {}
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(marker, event) {
console.log(this.props)
this.setState({
selectedMarker: marker
});
}
render() {
return (
<div style={{ padding: "24px 13px 2px 2px" }}>
<input type="button" value="My Location" style={{ marginBottom: "20px" }} onClick={(e) => this.onBtnClick()} />
<MapWithAMarker
selectedMarker={this.state.selectedMarker}
markers={this.props.resellerData}
onClick={this.handleClick}
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%`, padding: `61px 55px 55px 55px` }} />}
containerElement={<div style={{ height: `800px` }} />}
mapElement={<div style={{ height: `511px` }} />}
/>
</div>
);
}
}
Expecting
a Google map/
Markers of 'resellers'/
List the resellers in a list too/
On click of list item should populate info window like when we click on Markers/
First two points are working, Need a hand on the rest, Please help somebody
Thank you all for your time, I found the solution
Simply we can add the following line of code just after the infowindow close tag
<a onClick={onClick}>{marker.name}</a>