Are there alternatives to querySelectorAll in React? - javascript

I'm trying to refactor some javascript codes using React. What I'm trying to do is -> I have some elements which have the same className and I want to have control over each element. For this, in javascript I could just use the queryselectorAll and forEach functions, like
<Svg>
<circle cx="100" cy="60" r="20" class="human"></circle>
<line x1="100" y1="80" x2="100" y2="120" class="human"></line>
<line x1="70" x2="100" y1="75" y2="95" class="human"></line>
<line x1="130" x2="100" y1="75" y2="95" class="human"></line>
<line x1="70" x2="100" y1="140" y2="120" class="human"></line>
<line x1="130" x2="100" y1="140" y2="120" class="human"></line>
</Svg>
const wrongLetters = [];
window.addEventListener('keydown", (e) => {
if(e.keyCode >= 65 && e.keyCode <= 90) {
wrongLetters.push(e.key)
}
}
const humans = documentSelectorAll(".human")
humans.forEach((human, index) => {
if (index < wrongLetters.length) {
human.style.display = "block";
}
if (6 === wrongLetters.length) {
popUpContainer.style.display = "flex";
comment.innerText = "You have lost";
}
}); }
However, I assume it'd be different in React even if I change 'class' to 'className'? For this, I've already searched some relevant posts and tried to use 'ref' but still don't know exactly what to do in this case.
Any advice would be appreciated.
+edit/ What I'm trying to do is every time I add an element to 'wrongLetters' array, each element in Svg tag will be displayed. Each Svg element is set to 'display: none' as default in javascript

Put the wrongLetters into state that gets changed instead of pushing to the array. Then, in React, analyze that state to determine how many elements need to be hidden. Since this can encompass all of the functionality you're looking for, there's no need to be able to access the individual DOM elements with useRef or querySelectorAll:
const App = () => {
const [pressed, setPressed] = React.useState([]);
React.useEffect(() => {
window.addEventListener('keydown', (e) => {
if (!pressed.includes(e.keyCode) && e.keyCode >= 65 && e.keyCode <= 90) {
setPressed(pressed => [...pressed, e.keyCode]);
}
});
}, []);
return (
<svg>
<circle style={{display: pressed.length > 5 ? 'block' : 'none'}} cx="100" cy="60" r="20" stroke="black"></circle>
<line style={{display: pressed.length > 4 ? 'block' : 'none'}} x1="100" y1="80" x2="100" y2="120" stroke="black"></line>
<line style={{display: pressed.length > 3 ? 'block' : 'none'}} x1="70" x2="100" y1="75" y2="95" stroke="black"></line>
<line style={{display: pressed.length > 2 ? 'block' : 'none'}} x1="130" x2="100" y1="75" y2="95" stroke="black"></line>
<line style={{display: pressed.length > 1 ? 'block' : 'none'}} x1="70" x2="100" y1="140" y2="120" stroke="black"></line>
<line style={{display: pressed.length > 0 ? 'block' : 'none'}} x1="130" x2="100" y1="140" y2="120" stroke="black"></line>
</svg>
);
}
ReactDOM.render(<App />, document.querySelector('.react'));
line {
color: black;
}
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div class='react'></div>
That's the React way of doing things - use state when you can; avoid accessing/changing the DOM directly, just make the render reflect the state, and change the state when needed.

As I said in my comment, in react you'd have a component that renders those elements, updating them or rendering different elements according to changes in application or component state. You very, very rarely need to access the DOM directly in react.
Here's a rough implementation of the sort of thing I mean. There's a live/working copy of it on codesandbox:
import React, { useEffect } from "react";
import "./styles.css";
// an array of the svg elements; the component below renders
// a subset of these according to number of attempts.
// i'm not sure this is how i'd do this in the real world
// but it's good enough for this demo.
const segments = [
<circle cx="100" cy="60" r="20" class="human"></circle>,
<line x1="100" y1="80" x2="100" y2="120" class="human"></line>,
<line x1="70" x2="100" y1="75" y2="95" class="human"></line>,
<line x1="130" x2="100" y1="75" y2="95" class="human"></line>,
<line x1="70" x2="100" y1="140" y2="120" class="human"></line>,
<line x1="130" x2="100" y1="140" y2="120" class="human"></line>
];
export default function App() {
// track the number of attempts in component state
const [attempts, setAttempts] = React.useState(0);
// handler for keydown events that for this demo
// doesn't do anything besides increment the number of attempts
const onKeyDown = React.useCallback(() => setAttempts(attempts + 1), [
attempts
]);
useEffect(() => {
// when the component mounts, add the keydown listener
window.addEventListener("keydown", onKeyDown);
// when the component unmounts remove the listener
return () => window.removeEventListener("keydown", onKeyDown);
}, [onKeyDown]);
// get the visible subset of segments based on number of attempts
const visibleSegments = segments.slice(0, attempts);
// return the new markup
return (
<div className="App">
<svg viewBox="0 0 200 200" style={{ width: "300px" }}>
{visibleSegments}
</svg>
{attempts >= segments.length && (
<div>
<div>You Lose or whatever</div>
<button onClick={() => setAttempts(0)}>Reset</button>
</div>
)}
</div>
);
}

Brother if you want to access the DOM in React JS tou have to create ref using createRef() Hooks and then you can able to access the Dom in react like javascript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
you can acess the node by calling this.myRef.current method
const node = this.myRef.current;
You can add the same ref in multiple html element and when u called this.myRef.current then all the element you put the ref you can access...

Related

How to use linear gradient in rechart

I have to create this graph in React. I am using the rechart npm package to do so. But I am not able to get the corner radiuses and the linear gradient. I am open to use any other library if needed.
Image
What I have tried?
I have used rechart Pie component to achieve this. Here is the code
import React from 'react';
import { PieChart, Pie, Sector } from 'recharts';
import getDevice from '../../styles/devices';
const renderActiveShape = (props) => {
const { cx, cy, startAngle, endAngle, payload, innerRadius, outerRadius, z, cornerRadius } = props;
console.log(startAngle, endAngle)
return (
<g>
<text x={cx} y={cy - 20} dy={8} fontSize={z ? '16px' : "24px"} textAnchor="middle" fill="#001233" fontWeight="bold">
{/* {parseFloat(payload.value / 1000).toFixed(1)}K */}
{payload.value < 1000 ? payload.value : `${parseFloat(payload.value / 1000).toFixed(1)}K`}
</text>
<text x={cx} y={cy + 5} dy={8} fontSize="12px" textAnchor="middle" fill="#5C677D">
{payload.name}
</text>
<Sector
cx={cx}
cy={cy}
innerRadius={innerRadius}
outerRadius={outerRadius + 20}
startAngle={startAngle}
endAngle={endAngle}
fill={"#12A4ED"}
cornerRadius={payload.name === 'Deposit' ? cornerRadius : 0}
/>
<Sector
cx={cx}
cy={cy}
innerRadius={innerRadius - 18}
outerRadius={innerRadius - 10}
startAngle={startAngle}
endAngle={endAngle}
fill={"#7674740f"}
/>
{/* <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none" />
<circle cx={ex} cy={ey} r={2} fill={fill} stroke="none" /> */}
{/* <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} textAnchor={textAnchor} fill="#333">{`${value}%`}</text> */}
</g>
);
};
export default function Chart({ data }) {
// const [activeIndex, setActiveIndex] = useState(1)
// const onPieEnter = (_, index) => {
// setActiveIndex(index)
// };
const { isMobile } = getDevice()
return (
<PieChart width={400} height={350}>
<Pie
activeIndex={1}
activeShape={renderActiveShape}
data={data}
cx={200}
innerRadius={isMobile ? 60 : 80}
outerRadius={isMobile ? 100 : 120}
cornerRadius={isMobile ? 5 : 10}
fill="#7DC762"
dataKey="value"
z={isMobile}
>
</Pie>
</PieChart>
);
}
But what I get by using this is
Can anyone help how to achieve this? Any help is appreciated.
To add gradient color to your chart, you can do the following:
This is just an example:
<PieChart width={400} height={350}>
{/* This will allow to add color based on your need, so update it accordingly */}
<defs>
<linearGradient id="colorUv" x1="1" y1="1" x2="0" y2="0">
<stop offset="30%" stopColor="#6584FF" stopOpacity={0.5} />
<stop offset="95%" stopColor="#FFFFFF" stopOpacity={0.5} />
</linearGradient>
</defs>
<Pie
activeIndex={1}
activeShape={renderActiveShape}
data={data}
cx={200}
innerRadius={isMobile ? 60 : 80}
outerRadius={isMobile ? 100 : 120}
cornerRadius={isMobile ? 5 : 10}
fill="url(#colorUv)"//Add the id 'colorUv' which is used in linearGradient
dataKey="value"
z={isMobile}
></Pie>
</PieChart>

React Anchor Link on Hidden Item - Can't perform a React state update on an unmounted component

I've created a section on a site that is two sliders, the first slider is visible and on click the slide will display the corresponding slide beneath with the bottom slider initially starting as a display: none element. Each top slide also has a button on it that will anchor you down to the bottom slider to put it in a better view position.
If you navigate from the homepage onto this page and click on the anchor button first to display the content, the page does anchor down slightly but the content does not display, it also pastes the anchor link into the URL which doesn't seem to be how the working version behaves. On load the page is getting an error in the console saying Can't perform a React state update on an unmounted component.
You then have to click the object again or reload the page to get the anchor function/content to display as expected. Reloading the page also removes the React state console error as I'm assuming the component does mount.
The slider is built using Slick React slider and I'm using Gatsby Anchor Link Plugin and React Animate Height to perform both the hide/show height and anchor functions as I learnt in the project you can't just add a class to add height or just anchor stuff in React which is fun/backwards.
The component class for the page and the 2 components are below:
class AboutPage extends React.Component {
_isMounted = false;
constructor(props) {
super(props)
this.heroTextRef = React.createRef()
this.teamRef = React.createRef()
this.serviceGroupsRef = React.createRef()
this.state = {
nav1: null,
nav2: null,
isShow: false,
height: 0,
activeColor: false
}
this.openHeight = this.openHeight.bind(this);
this.closeHeight = this.closeHeight.bind(this);
}
openHeight = () => {
const { height } = this.state;
const { activeColor } = this.state;
this.setState({
height: 'auto',
activeColor: true,
});
};
closeHeight = () => {
const { height } = this.state;
const { activeColor } = this.state;
this.setState({
height: 0,
activeColor: false,
});
};
componentDidMount() {
this.setState({
nav1: this.slider1,
nav2: this.slider2
});
this._isMounted = false;
}
render() {
const { height } = this.state;
const team = get(this, 'props.data.contentfulPageContentStudio.theOrcaTeam')
return (
<Layout
location={this.props.location}
inversionRefs={[this.serviceGroupsRef, this.teamRef]}
>
<SEO
siteTitle={'About Us - ' + siteTitle}
/>
<TeamWrapper ref={this.teamRef} ref={this.serviceGroupsRef}>
<Container width={14}>
<Reveal
fraction={ANIMATION.revealFriction}
keyframes={customReveal}
triggerOnce
>
<TeamGridTitle id="topSlider">The Orca Team</TeamGridTitle>
</Reveal>
<Slider
dots={false}
infinite={false}
speed={500}
slidesToShow={3}
slidesToScroll={1}
swipeToSlide={true}
arrows={false}
asNavFor={this.state.nav2}
focusOnSelect={true}
responsive={[
{
breakpoint: 1024,
settings: {
slidesToShow: 2
}
}
]}
ref={slider => (this.slider1 = slider)}
className="top-slider"
>
{team.map((person, i) => (
<>
<TeamCard key={slugify(person.firstName)} index={i} person={person} onClick={this.openHeight} colour={this.state.activeColor}/>
</>
))}
</Slider>
</Container>
<AnchorTag id="bottomSlider" />
<AnimateHeight
duration={ 500 }
height={ height }
>
<SliderContainer>
<Slider
asNavFor={this.state.nav1}
ref={slider => (this.slider2 = slider)}
slidesToShow={1}
fade={true}
adaptiveHeight={true}
arrows={false}
dots={false}
infinite={false}
>
{team.map((person, i) => (
<>
<PersonBio key={slugify(person.lastName)} index={i} person={person} onClick={this.closeHeight}/>
</>
))}
</Slider>
</SliderContainer>
</AnimateHeight>
</TeamWrapper>
</Layout>
)
}
}
Top Slider Component:
const TeamCard = (props) => {
return (
<Card
onClick={props.onClick}
className={props.colour ? 'team-card' : null}
>
{props.person.image && <Img fluid={props.person.image.fluid} />}
<Info image={props.person.image} className="card-item">
<Name>
{props.person.firstName} {props.person.lastName}
</Name>
<Role className="small">{props.person.role}</Role>
<AnchorLink
to="/about/#bottomSlider"
title="Top Link"
>
<DownArrow version="1.1" x="0px" y="0px" viewBox="0 0 64 64" width="24" height="24">
<polyline
fill="none"
stroke="#FFFFFF"
strokeWidth="8"
strokeMiterlimit="10"
points="3.3,17.2 32,46.8 60.7,17.2 "/>
</DownArrow>
</AnchorLink>
</Info>
</Card>
)
}
Bottom Slider Component:
const PersonBio = (props) => {
return (
<Card className="card-block">
<Info>
<Container width={14}>
<FlexRow>
<PersonInfo>
<Name>
{props.person.firstName} {props.person.lastName}
</Name>
<Role className="small">{props.person.role}</Role>
<Meta>
{props.person.dribble && (
<IconLink
href={props.person.dribble}
target="_blank"
rel="noreferrer"
>
<IconDribbleSVG
alt={`${props.person.firstName} ${props.person.lastName} Dribbble link`}
/>
</IconLink>
)}
{props.person.instagram && (
<IconLink
href={props.person.instagram}
target="_blank"
rel="noreferrer"
>
<IconInstagramSVG
alt={`${props.person.firstName} ${props.person.lastName} Instagram link`}
/>
</IconLink>
)}
{props.person.linkedIn && (
<IconLink
href={props.person.linkedIn}
target="_blank"
rel="noreferrer"
>
<IconLinkedInSVG
alt={`${props.person.firstName} ${props.person.lastName} LinkedIn link`}
/>
</IconLink>
)}
</Meta>
</PersonInfo>
<PersonContent className="bio-text" dangerouslySetInnerHTML={{ __html: props.person.bio.bio }}>
</PersonContent>
</FlexRow>
<SvgRow>
<AnchorLink
to="/about/#topSlider"
title="Bottom Link"
>
<CloseBio x="0px" y="0px" viewBox="0 0 64 64" className="bio-close" onClick={props.onClick}>
<circle cx="32" cy="32" r="29.8"/>
<line x1="12.7" y1="32" x2="51.3" y2="32" className="crossLine1"/>
<line x1="12.7" y1="32" x2="51.3" y2="32" className="crossLine2"/>
</CloseBio>
</AnchorLink>
</SvgRow>
</Container>
</Info>
</Card>
)
}

using svg file to public folder vs. as component in nextjs

I need to use icons that are the same shape and have different sizes and colors.
At first, I was using a different file in the public folder.
ex) public/same-icon_red.svg, public/same-icon_blue.svg
But I think it's better to use it this way than this
//icon.js
export const Icon = ({fill, width, height}) => {
return (
<svg height={height} width={width} fill={fill} viewBox="0 0 24 24">
<path d="M0 0h24v24.../>
</svg>
);
}
//main.js
import Icon from "./icon"
...
return(
<>
...
<Icon width={24} height={24} fill={#000}/>
</>
)
But in this case, it bothers me that I don't use the public folder.
Which would be the best choice between the two?🤔

multiple mapbox react markers saved in state

I'm trying to add multiple markers to my map at once, but every time I add a new marker it replaces the previously placed one. I need the markers to be saved in the state so that they can all be submitted in one POST request. I have the API and Database set up, I just can't figure out this aspect of the UI.
The markers I am referring to are under the comment {/* USER ADDED MARKER */}
Thanks in advance for any help, I have been stuck on this for days.
import React, { useState, useEffect } from "react";
import ReactMapGL, { Marker, Popup } from "react-map-gl";
import { listLogEntries } from "./API";
import LogEntryForm from "./LogEntryForm";
const BasicMap = () => {
const [logEntries, setLogEntries] = useState([]);
const [showPopup, setShowPopup] = useState({});
const [showUserPopup, setShowUserPopup] = useState({});
const [addEntryLocation, setAddEntryLocation] = useState();
// viewport is all the infomation about the default map state
const [viewport, setViewport] = useState({
width: "100vw",
height: "100vh",
latitude: 52.950001,
longitude: -1.15,
zoom: 6
});
const getEntries = async () => {
const logEntries = await listLogEntries();
setLogEntries(logEntries);
};
useEffect(() => {
getEntries();
}, []);
const showAddMarkerPopup = event => {
const [longitude, latitude] = event.lngLat;
setAddEntryLocation({
latitude,
longitude
});
};
return (
<ReactMapGL
{...viewport}
mapStyle="mapbox://styles/hidden/ck7xdy1yo1bkj1ipmsbhe9c96"
mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_TOKEN}
onViewportChange={setViewport}
onClick={showAddMarkerPopup}
>
{/* USER ADDED MARKER */}
{addEntryLocation ? (
<>
<Marker
latitude={addEntryLocation.latitude}
longitude={addEntryLocation.longitude}
draggable
onDragEnd={showAddMarkerPopup}
onClick={() => setShowUserPopup(true)}
>
>
<div>
<svg
className="marker red"
style={{
height: `${6 * viewport.zoom}px`,
width: `${6 * viewport.zoom}px`
}}
version="1.1"
id="Layer_1"
x="0px"
y="0px"
viewBox="0 0 512 512"
>
<g>
<g>
<path
d="M256,0C153.755,0,70.573,83.182,70.573,185.426c0,126.888,165.939,313.167,173.004,321.035
c6.636,7.391,18.222,7.378,24.846,0c7.065-7.868,173.004-194.147,173.004-321.035C441.425,83.182,358.244,0,256,0z M256,278.719
c-51.442,0-93.292-41.851-93.292-93.293S204.559,92.134,256,92.134s93.291,41.851,93.291,93.293S307.441,278.719,256,278.719z"
/>
</g>
</g>
</svg>
</div>
</Marker>
{/* This Popup should have its own ? statement ' is clicked ' */}
<Popup
latitude={addEntryLocation.latitude}
longitude={addEntryLocation.longitude}
closeButton={true}
closeOnClick={true}
dynamicPosition={true}
// onClose={() => setShowPopup({})}
onClose={() => setAddEntryLocation(false)}
anchor="top"
>
<div className="popup">
<LogEntryForm
closeOnClick={true}
onClose={() => {
// setAddEntryLocation(null);
// getEntries();
setShowUserPopup(false);
}}
location={addEntryLocation}
/>
</div>
</Popup>
</>
) : null}
</ReactMapGL>
);
};
export default BasicMap;

How to bind the same event for each element in component without adding one by one manually?

I have a lot of elements in my component, because it's a SVG like:
export default mySVG = ({ onPress }) => (
<Svg>
<Circle ref='circle1' r="40" />
<Circle ref='circle2' r="30" />
<Circle ref='circle3' r="34" />
<Circle ref='circle4' r="35" />
<Circle ref='circle5' r="100" />
<Circle ref='circle6' />
<Rect />
<Path ref='path1' />
<Circle ref='circle7' />
<Circle ref='circle8' />
<Circle ref='circle9' />
<Rect />
<Path ref='path2' />
</Svg>
)
What I wanna do is bind onPress event to each one of those Circle and Path (except Rect).
So I can't bind event to <Svg> element and this code is just an example, it could much more bigger, so it could be hard to add onPress={onPress} (or any other repeat code) one by one.
Is there any way to bind the same event to each those automatically?
Edit 1:
I'm needing to handle some complex SVG, that's the reason that I'm avoiding to pass props to those components one by one, it could be thousand components.
Once component's clicked, it should pass it's ref as parameter.
I tried to set event by setNativeProps in componentDidMount like:
componentDidMount() {
for(let key in this.refs) {
this.refs[ key ].setNativeProps({
onPress: this.props.onPress.bind(this, key)
});
}
}
But it seems not working to set event, only to properties like fill.
If I understood you correctly, what you can do is to create a custom component that does the onPress event and then you can use that components rather than Circle and Path component directly. You can also override the onPress event if you want to this way.
export default class CustomCircle extends Component {
constructor(props) {
super(props);
}
_onPress() {
console.log('this is onPress');
if (this.props.onPress) {
this.props.onPress();
}
}
render() {
return <Circle { ...this.props } onPress={ this._onPress } />
}
}
export default class CustomPath extends Component {
constructor(props) {
super(props);
}
_onPress() {
console.log('this is onPress');
if (this.props.onPress) {
this.props.onPress();
}
}
render() {
return <Path { ...this.props } onPress={ this._onPress } />
}
}
export default mySVG = ({ onPress }) => (
<Svg>
<CustomCircle ref='circle1' onPress={onPress} />
<CustomCircle ref='circle2' />
<CustomCircle ref='circle3' />
<CustomCircle ref='circle4' />
<CustomCircle ref='circle5' />
<CustomCircle ref='circle6' />
<Rect />
<CustomPath ref='path1' />
<CustomCircle ref='circle7' />
<CustomCircle ref='circle8' />
<CustomCircle ref='circle9' />
<Rect />
<CustomPath ref='path2' />
</Svg>
)
Maybe you can do something like that:
const MyCircle = ({ onPress }) => {
return <MyCircle onPress={onPress} />
};
const MyPath = ({ onPress }) => {
return <MyPath onPress={onPress} />
};
export default mySVG = (props) => (
<Svg>
<MyCircle ref='circle1' {...props} />
<MyCircle ref='circle2' {...props} />
<MyCircle ref='circle3' {...props} />
<MyCircle ref='circle4' {...props} />
<MyCircle ref='circle5' {...props} />
<MyCircle ref='circle6' {...props} />
<Rect {...props} />
<MyPath ref='path1' {...props} />
<MyCircle ref='circle7' {...props} />
<MyCircle ref='circle8' {...props} />
<MyCircle ref='circle9' {...props} />
<Rect {...props} />
<MyPath ref='path2' {...props} />
</Svg>
)
EDIT:
But what about your structure of mySVG component? Is it fixed like that? Then maybe it would be easier if you create a list like
const svgElements = ['Circle', 'Circle', 'Circle', 'Circle', 'Circle', 'Circle', 'Rect', 'Path', 'Circle', etc...]
and map over it with function like:
export default ({onPress}) => {
const svgElements = ['Circle', 'Circle', 'Circle', 'Circle', 'Circle', 'Circle', 'Rect', 'Path', 'Circle'];
const svgContent = svgElements.map((svgElement, i) => {
switch(svgElement) {
case 'Circle':
return <Circle ref={`circle${i}`} onPress={onPress} />;
case 'Rect':
return <Rect ref={`rect${i}`} />;
case 'Path':
return <Path ref={`path${i}`} onPress={onPress} />;
}
});
return (
<Svg>
{svgContent}
</Svg>
)
}

Categories