Clone a React component that implements forwardRef - javascript

Lets say I have a base component that uses forwardRef like so:
const BaseMessage = React.forwardRef((props, ref) => (
<div ref={ref}>
{props.icon}
<h2>{props.title}</h2>
<p>{props.message}</p>
</div>
)
Now I want to create a second component, ErrorMessage that is essentially a copy of the BaseMessage but with a predefined value for props.icon, such that the icon prop is not needed to be set. Otherwise, its an exact copy of BaseMessage.
<ErrorMessage title="Oops!" message="Something went wrong when submitting the form. Please try again." />
I don't want to have to do this, since it feels weird to have two layers of forwardRef going on here:
const ErrorMessage = React.forwardRef(({icon, ...props}, ref) => (
<BaseMessage ref={ref} icon={<svg></svg>} {...props} />
))
Is there a way I can make a clone/copy of BaseMessage without having to reimplement forwardRef for ErrorMessage as well? I know there are utils out there like withProps from recompose but I'd like to avoid using a library if I can.

Try cloneElememt
React.cloneElement(BaseMessage, { icon: '' })

Related

Spread operator to pass all other props to a component. React.js

I'm having trouble understanding the spread operator when I want to pass all other props to a component.
Any help would be appreciated.
import React, { Fragment } from "react";
import SiteCard from "./SiteCard";
const SiteList = ({ sites }) => {
return (
<Fragment>
{sites.map((site) => {
return (
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
otherSiteProps={...site} // how can I pass the site props here?
/>
);
})}
</Fragment>
);
};
export default SiteList;
You are almost there with the solution.
You need to pass it as otherSiteProps={{...site}}.
This is if you want to pass site as an object to otherSiteProps property of SiteCard.
If you want to spread site and have multiple props for component SiteCard you do it like this:
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
{...sites}
/>
This in case that sites is an object. If site is an array, this wont work.
You just need to write:
<SiteCard
key={site.login.uuid}
image={site.picture.large}
firstName={site.name.first}
lastName={site.name.last}
city={site.location.city}
country={site.location.country}
sensors={site.dob.age}
{...site} // how can I pass the site props here?
/>
But wait, why you're making so complicated? You can just use:
<SiteCard {...site} />
Now, in your SiteCard component use required props.
And if I were you, I would not have separated SiteCard component for this scenario. I would just write:
{sites.map((site) => {
return (
// everything here I will utilize in html.
);
})}

How to access ref that was set in render

Hi I have some sort of the following code:
class First extends Component {
constructor(props){super(props)}
myfunction = () => { this.card //do stuff}
render() {
return(
<Component ref={ref => (this.card = ref)} />
)}
}
Why is it not possible for me to access the card in myfunction. Its telling me that it is undefined. I tried it with setting a this.card = React.createRef(); in the constructor but that didn't work either.
You are almost there, it is very likely that your child Component is not using a forwardRef, hence the error (from the React docs). ref (in a similar manner to key) is not directly accesible by default:
const MyComponent = React.forwardRef((props, ref) => (
<button ref={ref}>
{props.children}
</button>
));
// ☝️ now you can do <MyComponent ref={this.card} />
ref is, in the end, a DOMNode and should be treated as such, it can only reference an HTML node that will be rendered. You will see it as innerRef in some older libraries, which also works without the need for forwardRef in case it confuses you:
const MyComponent = ({ innerRef, children }) => (
<button ref={innerRef}>
{children}
</button>
));
// ☝️ now you can do <MyComponent innerRef={this.card} />
Lastly, if it's a component created by you, you will need to make sure you are passing the ref through forwardRef (or the innerRef) equivalent. If you are using a third-party component, you can test if it uses either ref or innerRef. If it doesn't, wrapping it around a div, although not ideal, may suffice (but it will not always work):
render() {
return (
<div ref={this.card}>
<MyComponent />
</div>
);
}
Now, a bit of explanation on refs and the lifecycle methods, which may help you understand the context better.
Render does not guarantee that refs have been set:
This is kind of a chicken-and-egg problem: you want the component to do something with the ref that points to a node, but React hasn't created the node itself. So what can we do?
There are two options:
1) If you need to pass the ref to render something else, check first if it's valid:
render() {
return (
<>
<MyComponent ref={this.card} />
{ this.card.current && <OtherComponent target={this.card.current} />
</>
);
}
2) If you are looking to do some sort of side-effect, componentDidMount will guarantee that the ref is set:
componentDidMount() {
if (this.card.current) {
console.log(this.card.current.classList);
}
}
Hope this makes it more clear!
Try this <Component ref={this.card} />

Using React.forwardRef inside render function directly

Is it safe to use React.forwardRef method directly inside render function of another component -
Example -
function Link() {
// --- SOME EXTENSIVE LOGIC AND PROPS CREATING GOES HERE ---
// --- OMITTED FOR SIMPLICITY ---
// TO DO: Remove forward ref as soon Next.js bug will be fixed -
// https://github.com/zeit/next.js/issues/7915
// Please note that Next.js Link component uses ref only to prefetch link
// based on its availability in view via IntersectionObserver API -
// https://github.com/zeit/next.js/blob/canary/packages/next/client/link.tsx#L119
const TempShallow = React.forwardRef(props =>
cloneElement(child, {
...props,
...baseProps,
onClick: handleClick
})
);
return (
<NextLink href={href} as={as} prefetch={prefetch} passHref {...otherProps}>
<TempShallow />
</NextLink>
);
}
As you see it's a temporary workaround for a bug in Next.js v9 - https://github.com/zeit/next.js/issues/7915.
Beware forwardRef affects reconciliation: element is always re-created on parent re-rendering.
Say
function App() {
const [,setState] = useState(null);
const Input = React.forwardRef((props, ref) => <input {...props} />)
return (
<div className="App">
<h1>Input something into inputs and then click button causing re-rendering</h1>
<Input placeholder="forwardRef" />
<input placeholder="native" />
<button onClick={setState}>change state to re-render</button>
</div>
);
}
You may see that after clicking button forwardRef-ed input is dropped and re-created so it's value becomes empty.
Not sure if this could be important for <Link> but in general it means things you'd expect to run only once per life time(say fetching data in componentDidMount or useEffect(...,[]) as alternative) will happen much more frequently.
So if choosing between this side effect and mocking warning I'd rather ignore Warning. Or create own <Link > that will not cause warnings.
[UPD] missed one thing: React checks forwardRef by reference in this case. So if you make forwardRef out of the render(so it's referentially the same) it will not be recreated:
const Input = React.forwardRef((props, ref) => <input {...props} />)
function App() {
const [,setState] = useState(null);
return (
<div className="App">
<h1>Input something into inputs and then click button causing re-rendering</h1>
<Input placeholder="forwardRef" />
<input placeholder="native" />
<button onClick={setState}>change state to re-render</button>
</div>
);
}
But still I believe it's safer to ignore warning than to introduce such a workaround.
Code above has worse readability to me and is confusing("why ref is not processed at all? was it intentional? why this forwardRef is here and not in component's file?")
I concurr with skyboyer, I'll add that it might be possible to create the forwardRef component outside of the render function to avoid re-creating the component each render. To be checked.
const TempShallow = React.forwardRef(({ child, ...props }) => React.cloneElement(child, props))
function Link() {
// --- SOME EXTENSIVE LOGIC AND PROPS CREATING GOES HERE ---
// --- OMITTED FOR SIMPLICITY ---
// TO DO: Remove forward ref as soon Next.js bug will be fixed -
// https://github.com/zeit/next.js/issues/7915
// Please note that Next.js Link component uses ref only to prefetch link
// based on its availability in view via IntersectionObserver API -
// https://github.com/zeit/next.js/blob/canary/packages/next/client/link.tsx#L119
return (
<NextLink href={href} as={as} prefetch={prefetch} passHref {...otherProps}>
<TempShallow {...props} {...baseprops} child={child} onClick={onClick} />
</NextLink>
)
}

How to get react-pose working with class components?

I've followed the documentation and this blog post but I'm struggling to get anything to work.
Locally, I get the following error: HEY, LISTEN! No valid DOM ref found. If you're converting an existing component via posed(Component), you must ensure you're passing the ref to the host DOM node via the React.forwardRef function.
So I've attempted to forward the ref:
class ColorCheckbox extends Component {
setRef = ref => (this.ref = ref);
constructor(props) {
super(props);
}
render() {
const { key, children, color } = this.props;
return (
<button
ref={this.setRef}
key={key}
style={{
...style.box,
background: color,
}}
>
{children}
</button>
);
}
}
export default forwardRef((props, innerRef) => (
<ColorCheckbox ref={innerRef} {...props} />
));
Which is working as I'm able to console.log the ref inside my parent Component:
ColorCheckbox {props: Object, context: Object, refs: Object, updater: Object, setRef: function ()…}
"ref"
However, I still receive the message (above) of No valid DOM ref found....
Here's a simple Codesandbox describing my issue.
About the Codesandbox:
I am getting cross-origin errors in this Sandbox (they do not occur locally). If you change line 14 to be ColorCheckbox the cross-origin error goes...
Any ideas?
When you call forwardRef on a class based component and try to pass the ref through the ref attribute it will not work. The documentation example will only work for regular DOM elements. Rather try doing the following:
export default forwardRef((props, innerRef) => (
<ColorCheckbox forwardRef={innerRef} {...props} />
));
I've just used an arbitrary name, so in this case forwardRef, to pass the ref as a prop. In your class based component I've changed the part where the ref is set on the button to this:
const { key, children, selected, color, forwardRef } = this.props;
return (
<button
ref={forwardRef}
key={key}
style={{
...
The following approach, which they feature in their blog post, will only work for regular DOM elements and styled-components:
const MyComponent = forwardRef((props, ref) => (
<div ref={ref} {...props} />
));
Please refer to my Codesandbox fork to see a working example.

how do you use computed property names in HOCs?

I have a HOC like so:
export const authenticateUser = WrappedComponent => (props) => {
return props.authenticated ? <WrappedComponent {...props} /> : <div> Please log in to continue </div>
}
but this is semi reusable. I would like to reuse this HOC in many places but instead of hardcoding props.authenticated I would like to do something like props[authenticator] where authenticator is what ever I pass down. for example
I would like it to be the following
props.admin
props.authenticated
props.manager
on different occasions?
how can I pass this down?
i have tried adding it as a second argument/prop
but when I do this
const Auth = authenticateUser(welcomeScreen, 'admin')
it breaks
any ideas?

Categories

Resources