Styling HighCharts reset Zoom button with Material UI button - css

I'm working on a project where we're using HighCharts and Material UI for UI components. Is there any way I can use the Material UI button component in place of the standard HighChart reset Zoom button?

This button has limited styling options, but you can replace it by a custom one in simple steps:
Overwrite method which is responsible for showing the default button.
Highcharts.Chart.prototype.showResetZoom = function () {};
Add and position a custom button with linked chart.zoomOut method called on click:
const App = () => {
const chartComponent = useRef(null);
const [isZoomed, setIsZoomed] = useState(false);
const [options] = useState({
chart: {
zoomType: "x",
events: {
selection: function (e) {
if (e.resetSelection) {
setIsZoomed(false);
} else {
setIsZoomed(true);
}
}
}
},
...
});
const resetZoom = () => {
if (chartComponent && chartComponent.current) {
chartComponent.current.chart.zoomOut();
}
};
return (
<div style={{ position: "relative" }}>
<HighchartsReact
ref={chartComponent}
highcharts={Highcharts}
options={options}
/>
{isZoomed && (
<Button
style={{ position: "absolute", top: 50, right: 10 }}
onClick={resetZoom}
color="primary"
>
Reset zoom
</Button>
)}
</div>
);
};
Live demo: https://codesandbox.io/s/highcharts-react-demo-forked-ssqk9?file=/demo.jsx
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#zoomOut

Related

add div to map leaflet reactjs

Good morning
I would like to add a block div on my leaflet card with text in the div Reactjs.
but it does not show on the map. It is displayed under the map, I tried with z-index but I did not succeed
anyone have a solution please?
<div >
<MapContainer center={center} zoom={zoom} style={{ height: "90vh", opacity: 'O,33' }}>
<TileLayer attribution='&copy OpenStreetMap contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<Markers marker={mark} />
<div>Test</div>
</MapContainer >
</div>);```
You can use z-index, however you will also have to set position to something other than default static. e.g. position: absolute
I would recommend to look into the built in leaflet-control classes. I use a custom controller to add stuff above the map:
import L from "leaflet";
import React, { useEffect, useRef } from "react";
const ControlClasses = {
bottomleft: "leaflet-bottom leaflet-left",
bottomright: "leaflet-bottom leaflet-right",
topleft: "leaflet-top leaflet-left",
topright: "leaflet-top leaflet-right",
};
type ControlPosition = keyof typeof ControlClasses;
export interface LeafLetControlProps {
position?: ControlPosition;
children?: React.ReactNode;
offset?: [number, number];
}
const LeafletControl: React.FC<LeafLetControlProps> = ({
position,
children,
offset = [0, 0],
}) => {
const divRef = useRef(null);
useEffect(() => {
if (divRef.current) {
L.DomEvent.disableClickPropagation(divRef.current);
L.DomEvent.disableScrollPropagation(divRef.current);
}
});
return (
// #ts-ignore
<div
style={{
marginLeft: offset[0],
marginTop: offset[1],
}}
ref={divRef}
className={position && ControlClasses[position]}
>
<div className={"leaflet-control"}>{children}</div>
</div>
);
};
export default LeafletControl;

Change css-module dynamically on React

I have a canvas like this in Component
It can change the pointer to crosshair when cursor is entered on Canvas.
import styles from '../css/basic-styles.module.css';
const ImagePreview = () =>{
[mode,setMode] = useState(0);
changeMode(mode){
setMode(mode);
}
return (){
<canvas className={styles.canvas} width=200 height=200></canvas>
}
}
in css
canvas:hover{
/*cursor:pointer;*/
cursor:crosshair;
}
Now I want to change the css dynamically depending on the mode value.
I want to use pointer when mode is 1
I should quite use css? or is there any method to make it work?
Please see the solution below. It is also available in the sandbox.. Ignore the vanilla react solution it included for the snippet runner. Click Run Code Snippet to see preview here.
/* Solution
const ImagePreview = () => {
const [mode, setMode] = useState(0);
return (
<canvas
onMouseEnter={() => setMode(1)}
onMouseLeave={() => setMode(0)}
style={{
backgroundColor: "teal",
cursor: mode ? "crosshair" : "pointer"
}}
width={200}
height={200}
/>
);
};
*/
// This is so it can work in Stackoverflow snippet preview. //
const ImagePreview = () => {
const [mode, setMode] = React.useState(0);
const canvasCfg = {
onMouseEnter: () => setMode(1),
onMouseLeave: () => setMode(0),
style: { backgroundColor: "teal", cursor: mode ? "crosshair" : "pointer"},
width: 200,
height: 200
}
return React.createElement('canvas', canvasCfg)
}
const domContainer = document.querySelector('#app');
const root = ReactDOM.createRoot(domContainer);
root.render(React.createElement(ImagePreview));
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
<div id="app"></div>
create two classes like this
canvas1:hover{
cursor:pointer;
}
canvas2:hover{
cursor:crosshair;
}
and use it conditionally based on mode like
import styles from '../css/basic-styles.module.css';
const ImagePreview = () =>{
[mode,setMode] = useState(0);
changeMode(mode){
setMode(mode);
}
return (){
<canvas className={mode == 1 ? styles.canvas1 : styles.canvas2} width=200 height=200></canvas>
}
}
you can also use classes without :hover , this will also give the desired result because of cursor property
.canvas1{
cursor: pointer;
}
.canvas2{
cursor: crosshair;
}

Style for disabled property in css object model

For some reason, I need to pass CSS objects using CSS object model inside a react component. Here, I need styles for buttons when they are disabled and when not disabled. Like we do with: backgroundColor, borderRadius and such.
const controlButton = {
backgroundColor:"#006191",
padding:"10px 20px",
border:"none",
borderRadius:"5px"
}
This is where im trying to use it and wanto to pass the object in style.
const App = () => {
const [disable, setDisable] = useState(false);
return(
<div>
<button style={(style.active, disable && style.disable)}>Click</button>
</div>
)
}
Not too elegant but working solution.
import React, { useState } from 'react';
const controlButtonEnabled = {
backgroundColor: '#006191',
padding: '10px 20px',
border: 'none',
borderRadius: '5px',
};
const controlButtonDisabled = {
backgroundColor: 'gray',
padding: '10px 20px',
border: 'none',
borderRadius: '5px',
};
export default function MyAwesomeComponent() {
const [enabled, setEnabled] = useState(true);
const onEnable = () => {
setEnabled(!enabled);
};
return (
<button
onClick={onEnable}
style={enabled ? controlButtonEnabled : controlButtonDisabled}
>
Button
</button>
>
);
}

Changing CSS styles when an event fires

I'm trying to integrate THEOPlayer in my project and I want to customize styles depending on certain events. For instance, I would love to hide the toolbar and show an overlay image when the video is paused.
They do expose some CSS classes that I can change manually but my question is, how do I change the values in CSS on a specific event. Since the player is imported as a single JSX element I don't know how to add custom classes to its specific parts. So I would like to know if there is another way.
Here is a component where an instance of Player is created:
class Player extends React.Component {
_player = null;
_el = React.createRef();
componentDidMount() {
const { source, onPlay, onPause } = this.props;
if (this._el.current) {
this._player = new window.THEOplayer.Player(this._el.current, {
libraryLocation:
"https://cdn.myth.theoplayer.com/7aff3fa6-f92e-45f9-a40e-1bce9911b073/",
});
this._player.source = source;
this._player.addEventListener("play", onPlay);
this._player.addEventListener("pause", onPause);
}
}
componentWillUnmount() {
if (this._player) {
this._player.destroy();
}
}
render() {
return (
<div
className={
"theoplayer-container video-js theoplayer-skin vjs-16-9 THEOplayer"
}
ref={this._el}
>
</div>
);
}
}
export default Player;
And that's a part of code where I want to change styles onPlay and onPause
<div className={"player-container"}>
<Player
source={source}
onPlay={() => {
console.log("playing");
}}
onPause={() => {
console.log("paused");
}}
/>
</div>
Use like this
state = {
play: false,
pause: true,
}
const playFn = () => {
this.setState = ({
play: true,
pause: false,
})
}
const pauseFn = () => {
this.setState = ({
play: false,
pause: true,
})
}
<div className={"player-container"}>
<Player
source={source}
onPlay={playFn}
onPause={pauseFn}
activatePlayClasses={play}
activatePauseClasses={pause}
bg={'https://example/example.jpg'}
/>
</div>
// on Player component
const { source, onPlay, onPause, activatePauseClasses, activatePlayClasses , bg} = this.props;
render() {
return (
<div
className={
`theoplayer-container video-js theoplayer-skin vjs-16-9 THEOplayer
${activatePauseClasses ? 'your pause class' : ''}
${activatePlayClasses ? 'your play class' : ''}`
}
style={{backgroundImage: `url(${bg})`}}
ref={this._el}
>
</div>
);
}
I have updated code

Changing styles during clicking

I have ReactJS project and I want to change colour of button during clicking. I know that it is a Ripple API but it's very incomprehensible to use it. Could someone advise me how can I do that?
I've tried to create two elements - parent and child - and changed background of child to transparent while clicking. Unfortunately I have also 'classes' object responsible for changing class if button is active and it is just not working.
My code below:
import React, { Component } from 'react';
import { withStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import PropTypes from 'prop-types';
import styles from './MydButton.style';
class MyButton extends Component {
constructor(props) {
super(props);
this.state = {
isClicked: false
};
}
handleClick = () => {
this.setState({ isClicked: !this.state.isClicked });
}
render() {
const {
classes,
children,
color,
disabled,
className,
onClick,
type,
border,
...props
} = this.props;
const myClass = this.state.isClicked ? 'auxClass' : 'buttonDefaultRoot';
return (
<div className={classes.parentRoot} >
<Button
classes={{
root: disabled
? classes.buttonDisabledRoot
: classes.buttonRoot,
label: disabled
? classes.buttonLabelDisabled
: classes.buttonLabel,
}}
{...props}
onClick={this.handleClick}
className={myClass}
disabled={disabled}
type={type === undefined ? 'button' : type}
>
{children}
</Button>
</div>
)
}
};
MyButton.propTypes = {
children: PropTypes.string.isRequired,
disabled: PropTypes.bool,
classes: PropTypes.object.isRequired,
};
MyButton.defaultProps = {
disabled: false,
};
export default withStyles(styles)(MyButton);
and styles:
const buttonRoot = {
border: 0,
height: 48,
width: '100%',
}
export default theme => ({
buttonDefaultRoot: {
...buttonRoot,
transition: 'all 1s ease-in-out',
backgroundImage: 'linear-gradient(to right, #F59C81, #E65DA2, #E65DA2, #B13A97, #881E8E)',
boxShadow: '0px 1px 3px rgba(0, 0, 0, 0.16)',
backgroundSize: '300% 100%',
marginTop: 0,
'&:hover': {
backgroundPosition: '100% 0%',
transition: 'all 1s ease-in-out',
}
},
parentRoot: {
...buttonRoot,
backgroundColor: 'red',
backgroundSize: '300% 100%',
marginTop: 36,
},
auxClass: {
backgroundImage: 'none',
},
Material UI Core for ReactJS
The documentation is very good. I have updated my answer to accomodate the specific needs of this question. I have also included two general solutions for anyone who stumbles upon this question.
Tailored Solution:
Changes background color of button from classes.buttonDefaultRoot (a color defined by owner of question) to the gradient defined by the owner of this question.
First step, have a variable stored in state. You can call it whatever you want, but I'm calling bgButton. Set this to this.props.classes.buttonDefaultRoot like so:
state = {
bgButton: this.props.classes.buttonDefaultRoot,
}
Next, you want to define your function that will handle the click. Again, call it what you want. I will call it handleClick.
handleClick = () => {
const { classes } = this.props; //this grabs your css style theme
this.setState({ bgButton: classes.parentRoot.auxClass }); //accessing styles
};
A couple of things are happening here. First, I am destructuring props. So, I am creating a new const variable called classes that has the same value as this.props.classes. The classes contains a set of objects that defines your css styles for your buttons, margins, etc. You can access those styles just like you would if you were trying to get the value of a prop in an obj.
In this case you can access your button style by doing, classes.buttonDefaultRoot. That takes care of your handle click function.
Last step: render the button. In your render method you want to grab your bgButton from state like so:
render() {
const { bgButton } = this.state;
Then you want to assign your className of your button to bgButton and add the onClick functionality like this (this follows the Material UI Core documentation):
<Button variant="contained" color="primary" className={classNames(bgButton)} onClick={this.handleClick}>Button Name</Button>
Putting it all together you get this:
import React, { Component } from "react";
import Button from "#material-ui/core/Button";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "#material-ui/core/styles";
export default theme => ({ ... }) //not going to copy all of this
class MyButton extends Component {
state = {
bgButton: null
};
handleClick = () => {
const { classes } = this.props;
this.setState({ bgButton: classes.parentRoot.auxClass });
};
render() {
const { bgButton } = this.state;
return (
<div className={classes.container}>
<Button
variant="contained"
color="primary"
className={classNames(bgButton)}
onClick={this.handleClick}
>
Custom CSS
</Button>
</div>
);
}
}
MyButton.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(MyButton);
General Solution
This solution is for those who want to use the predefined colors, i.e. default, primary, secondary, inherit. This implementation does not need the PropTypes or className imports. This will change the color from the predefined blue to the predefined pink. That's it.
state = {
bgButton: "primary",
}
handleClick = () => {
this.setState({ bgButton: "secondary" });
}
render() {
const { bgButton } = this.state;
return(
...
<Button
onClick = {this.handleClick}
variant = "contained" //checked Material UI documentation
color={bgButton}
> ..etc.
General Solution 2
To accommodate your custom styles to the button, you would have to import PropTypes and classNames and take a similar approach as the tailored solution above. The only difference here will be my syntax and class name. I am closely following the documentation here so you can easily follow along and readjust where necessary.
import React, { Component } from "react";
import Button from "#material-ui/core/Button";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "#material-ui/core/styles";
import purple from "#material-ui/core/colors/purple";
const styles = theme => ({
container: {
display: "flex",
flexWrap: "wrap"
},
margin: {
margin: theme.spacing.unit
},
cssRoot: {
color: theme.palette.getContrastText(purple[500]),
backgroundColor: purple[500],
"&:hover": {
backgroundColor: purple[700]
}
},
bootstrapRoot: {
boxShadow: "none",
textTransform: "none",
fontSize: 16,
padding: "6px 12px",
border: "1px solid",
backgroundColor: "#007bff",
borderColor: "#007bff",
fontFamily: [
"-apple-system",
"BlinkMacSystemFont",
'"Segoe UI"',
"Roboto",
'"Helvetica Neue"',
"Arial",
"sans-serif",
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"'
].join(","),
"&:hover": {
backgroundColor: "#0069d9",
borderColor: "#0062cc"
},
"&:active": {
boxShadow: "none",
backgroundColor: "#0062cc",
borderColor: "#005cbf"
},
"&:focus": {
boxShadow: "0 0 0 0.2rem rgba(0,123,255,.5)"
}
}
});
class MyButton extends Component {
state = {
bgButton: null
};
handleClick = () => {
const { classes } = this.props;
this.setState({ bgButton: classes.cssRoot });
};
render() {
const { classes } = this.props; //this gives you access to all styles defined above, so in your className prop for your HTML tags you can put classes.container, classes.margin, classes.cssRoot, or classes.bootstrapRoot in this example.
const { bgButton } = this.state;
return (
<div className={classes.container}>
<Button
variant="contained"
color="primary"
className={classNames(bgButton)}
onClick={this.handleClick}
>
Custom CSS
</Button>
</div>
);
}
}
MyButton.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(MyButton);
A tip. You no longer need a constructor or to bind methods.
Hope this helps.

Resources