Get the ref of a functional component dynamically - ReactJS - javascript

I need to access my ref with a string variable that passed from props and contains the ref name that I want to get. something like this:
function MyComponent(props) {
const myFirstRef = useRef();
const mySecondRef = useRef();
const myThirdRef = useRef();
function handleClick() {
const targetRef = props.targetRef;
// The `targetRef` is a string that contains
// the name of the one of the above refs!
// I need to get my ref by string
// ...
}
return (
<div ref={myFirstRef}>
<div ref={mySecondRef}>
<div ref={myThirdRef}>
<button onClick={handleClick}>Find Ref and Do Something</button>
</div>
</div>
</div>
)
}
The targetRef is a string that contains the name of the above refs!
In class components there is this.refs and I could do what I want easily.

You may want to use a dictionary as object for mapping given key targetRef to a specific reference:
const ref = useRef({ first: undefined, second: undefined, third: undefined });
ref.current[targetRef];
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
const RefContainer = ({ targetRef }) => {
const ref = useRef({ first: undefined, second: undefined, third: undefined });
const handleClick = () => {
const coolRef = ref.current[targetRef];
console.log(coolRef);
};
return (
<div ref={node => (ref.current.first = node)}>
<div ref={node => (ref.current.second = node)}>
<div ref={node => (ref.current.third = node)}>
<button onClick={handleClick}>Find Ref and Do Something</button>
</div>
</div>
</div>
);
};
const App = () => {
return <RefContainer targetRef="third" />;
};
ReactDOM.render(<App />, document.getElementById('root'));

Related

How to use React.forwardRef?

I want to pass ref to a child component with forwardRef, but current for the given ref is always null. Why?
Consider this simple example:
// Details.jsx
import { useRef, forwardRef } from 'react';
const Details = () => {
const usernameRef = useRef(null);
const InputClipboardButton = React.forwardRef((props, ref) => (
<ClipboardButton targetInputRef={ref} />
));
return (
<div>
<input type="text" ref={usernameRef} />
<InputClipboardButton ref={usernameRef} />
</div>
);
};
// ClipboardButton.jsx
const ClipboardButton = ({ targetInputRef }) => {
const copyToClipboard = () => {
console.log(targetInputRef);
}
<button onClick={copyToClipboard}>
Copy
</button>
};
When using forwardRef you must be mindful of the order of the parameters passed (props and ref):
You can define the component like so:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
Note how forwardRef takes two parameters:
The props
The ref being forwarded
You may also destructure the props value, as well as call the ref property a different name:
const FancyButton = React.forwardRef(({
btnType,
children
}, forwardedRef) => (
<button ref={forwardedRef} type={btnType} className="FancyButton">
{children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref} btnType="button">Click me!</FancyButton>;
Example adapted from React Docs
Clipboard Button is a component, so you must use forwardRef in this component as well
const ClipboardButton = forwardRef((props,ref) => {
const copyToClipboard = () => {
console.log(ref);
}
<button onClick={copyToClipboard}>
Copy
</button>
});

Get value from response and transfer to another component in React

I have this handleSubmit that returns me a key (verifyCode) that I should use in another component. How can I pass this verifyCode to another component?
const SendForm = ({ someValues }) => {
const handleSubmitAccount = () => {
dispatch(createAccount(id, username))
.then((response) => {
// I get this value from data.response, its works
const { verifyCode } = response;
})
.catch(() => {
});
};
return(
//the form with handleSubmitAccount()
)
}
export default SendForm;
The other component is not a child component, it is loaded after this submit step. But I don't know how to transfer the const verifyCode.
This is the view where the components are loaded, it's a step view, one is loaded after the other, I need to get the const verifyCode in FormConfirmation
<SendForm onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
<FormConfirmation onSubmit={handleStepSubmit} onFieldSubmit={handleFieldSubmit} />
Does anyone know how I can do this?
You need to move up the state to a component that has both as children and then pass down a function that updates as a prop
import React from "react";
export default function App() {
const [value, setValue] = React.useState(0);
return (
<div className="App">
<Updater onClick={() => setValue(value + 1)} />
<ValueDisplay number={value} />
</div>
);
}
const Updater = (props) => <div onClick={props.onClick}>Update State</div>;
const ValueDisplay = (props) => <div>{props.number}</div>;
Check out the docs here
For more complex component structures or where your passing down many levels you may want to look into reactContext
import React from "react";
//Set Default Context
const valueContext = React.createContext({ value: 0, setValue: undefined });
export default function App() {
const [value, setValue] = React.useState(0);
return (
<div className="App">
{/** Pass in state and setter as value */}
<valueContext.Provider value={{ value: value, setValue }}>
<Updater />
<ValueDisplay />
</valueContext.Provider>
</div>
);
}
const Updater = () => {
/** Access context with hook */
const context = React.useContext(valueContext);
return (
<div onClick={() => context.setValue(context.value + 1)}>Update State</div>
);
};
const ValueDisplay = () => {
/** Access context with hook */
const context = React.useContext(valueContext);
return <div>{context?.value}</div>;
};

Get previous props value with React Hooks

I am using usePreviousValue custom hook to get previous props value from my component:
const usePreviousValue = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const MyComponent = ({ count }) => {
const prevCount = usePreviousValue(count)
return (<div> {count} | {prevCount}</div>)
}
But in this case, in prevCount I always have only the first count prop value when a component was rendered, and the next updated prop value is never assigned to it. Are there any ways to properly compare nextProp and prevProp with functional React components?
Your code sample seems to be working just fine. How exactly are you using the component? Try to run the snippet below:
const { useEffect, useRef, useState } = React;
const usePreviousValue = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const MyComponent = ({ count }) => {
const prevCount = usePreviousValue(count);
return (<div> {count} | {prevCount}</div>);
}
function App() {
const [count, setCount] = useState(0);
return (
<div>
<MyComponent count={count} />
<button
onClick={() => setCount((prevCount) => prevCount + 1)}
>
Count++
</button>
</div>
);
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
As previously answered, the easiest way to do it is using a custom hook:
import isEqual from "lodash/isEqual";
import { useEffect, useRef } from "react";
const useComponentDidUpdate = (callback, data, checkIfIsEqual) => {
const prevData = useRef(data);
useEffect(() => {
const isTheSame = checkIfIsEqual ? isEqual(data, prevData) : undefined;
callback(prevData.current, isTheSame);
prevData.current = data;
}, [data]);
return null;
};
export default useComponentDidUpdate;
Then in your component:
const Component = ({age})=>{
const [state, setState] = useState({name: 'John', age})
useComponentDidUpdate(prevStateAndProps=>{
if(prevStateAndProps.age !== age || prevStateAndProps.state.name !== state.name){
// do something
}
}, {state, age})
...
}

How to remove an element from an array dynamically? React.js

There are two components, I want to implement an element array using the useContext hook, but when the button is clicked, the element is not removed, but on the contrary, there are more of them. Tell me what is wrong here. I would be very grateful!
First component:
import React from 'react';
import CartItem from './CartItem';
import Context from '../Context';
function Cart() {
let sum = 0;
let arrPrice = [];
let [products, setProducts] = React.useState([]);
let loacalProsucts = JSON.parse(localStorage.getItem('products'));
if(loacalProsucts === null) {
return(
<div className="EmptyCart">
<h1>Cart is empty</h1>
</div>
)
} else {
{loacalProsucts.map(item => products.push(item))}
{loacalProsucts.map(item => arrPrice.push(JSON.parse(item.total)))}
}
for(let i in arrPrice) {
sum += arrPrice[i];
}
function removeItem(id) {
setProducts(
products.filter(item => item.id !== id)
)
}
return(
<Context.Provider value={{removeItem}}>
<div className="Cart">
<h1>Your purchases:</h1>
<CartItem products = {products} />
<h1>Total: {sum}$</h1>
</div>
</Context.Provider>
)
}
Second component:
import React, { useContext } from 'react';
import Context from '../Context';
function CartList({products}) {
const {removeItem} = useContext(Context);
return(
<div className="CartList">
<img src={products.image} />
<h2>{products.name}</h2>
<h3 className="CartInfo">{products.kg}kg.</h3>
<h2 className="CartInfo">{products.total}$</h2>
<button className="CartInfo" onClick={() => removeItem(products.id)}>×</button>
</div>
);
}
export default CartList;
Component with a context:
import React from 'react';
const Context = React.createContext();
export default Context;
Adding to the comment above ^^
It's almost always a mistake to have initialization expressions inside your render loop (ie, outside of hooks). You'll also want to avoid mutating your local state, that's why useState returns a setter.
Totally untested:
function Cart() {
let [sum, setSum] = React.useState();
const loacalProsucts = useMemo(() => JSON.parse(localStorage.getItem('products')));
// Init products with local products if they exist
let [products, setProducts] = React.useState(loacalProsucts || []);
useEffect(() => {
// This is actually derived state so the whole thing
// could be replaced with
// const sum = products.reduce((a, c) => a + c?.total, 0);
setSum(products.reduce((a, c) => a + c?.total, 0));
}, [products]);
function removeItem(id) {
setProducts(
products.filter(item => item.id !== id)
)
}
...

How to create dynamic element in react?

I am trying to create dynamically element on button click and append it to one of the classes by using ref.
I can use document.createElement but from what I read do not use it in react
For example I want to add an element of <p> to div with class name of classes.elements by clicking the button
import React, { useRef } from 'react'
import classes from './AddElement.scss'
const AddElement = (props) => {
const elementRef = useRef(null)
const addElement = () => {
<p>This is paragraph</p>
}
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div ref={elementRef} className={classes.elements}>
</div>
</div>
)
}
export default AddElement;
You could try using the useState hook like this :
import React, { useState } from 'react';
import classes from './AddElement.scss';
const AddElement = () => {
const [dynamicElems, setDynamicElems] = useState([]);
const addElement = () => {
// Creates the dynamic paragraph
const newDynamicElem = <p className={classes.elements}>This is paragraph</p>;
// adds it to the state
setDynamicElems(() => [...dynamicElems, newDynamicElem]);
};
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div className={classes.elements}>{dynamicElems}</div>
</div>
);
};
export default AddElement;
const AddElement = (props) => {
const [dynamicCompList, setDynamicCompList] = useState([]);
const addElement = () => {
const dynamicEl = React.createElement("p", {}, "This is paragraph");
setDynamicCompList(dynamicCompList.concat(dynamicEl));
}
return (
<div>
<button onClick={() => addElement()}>Click here</button>
<div className={classes.elements}>
{dynamicCompList}
</div>
</div>
)
}
export default AddElement;
Try this:
const addElement = () => {
const para = document.createElement("p");
para.innerHTML = 'Hello';
elementRef.current.appendChild(para);
};
<div ref={elementRef}></div>
<button onClick={addElement}>Click me</button>
Approach 1
import React, { useRef, useState } from "react";
import classes from "./App.module.scss";
export default function App() {
const componetRef = useRef(null);
const [contentValue, setContentValue] = useState([]);
const addElement = () => {
const content = "this is para";
const type = componetRef.current.dataset.type || "p";
const classNames = componetRef.current.className;
const elemnt = React.createElement(type, { key: Date.now() }, content);
setContentValue([
...contentValue, // If you dont want to make it multiple times. just remove it
elemnt
]);
};
return (
<div className="App">
<button onClick={addElement}>Click here</button>
<div data-type="h1" ref={componetRef} className={classes.tag1}>
{contentValue}
</div>
</div>
);
}
Approach 2
import React, { useState } from "react";
import classes from "./App.module.scss";
const NewComponent = ({ classNames, content }) => {
return (
<div className={classNames} dangerouslySetInnerHTML={{ __html: content }} />
);
};
export default function App() {
// const classRef = useRef(null);
const [multiple, setMultiple] = useState([]);
const addElement = (e) => {
const classNames = e.target.dataset.class;
const content = e.target.dataset.content;
setMultiple([
...multiple, // If you dont want to make it multiple times. just remove it
<NewComponent
key={Date.now()}
classNames={classNames}
content={content}
/>
]);
};
return (
<div className="App">
<button
onClick={addElement}
data-class={classes.tag1}
data-content={"<p>asdasd</p>"}
>
Click here
</button>
{multiple}
</div>
);
}
Let me know if you have more question.
Here is sandbox

Categories

Resources