Better API for rich components
See original GitHub issueThe props injected into child components can conflict with the other props of the child component. Example:
import { forwardRef, useRef } from "react";
import Draggable from "react-draggable";
import { italic } from "./App.module.css";
const Component1 = forwardRef((props, ref) => {
const { className } = props;
console.log(props);
return (
<div {...props} ref={ref}>
<span>This should not be italic</span>
<br />
<span className={className}>This should be italic</span>
</div>
);
});
export default function App() {
const ref = useRef(null);
return (
<Draggable nodeRef={ref}>
<Component1 ref={ref} className={italic} />
</Draggable>
);
}
Link to codesandbox: https://codesandbox.io/s/react-draggable-bug-3-p99yd?file=/src/App.js
In this example, creating <div {...props} />
results in the div getting unwanted props.
There should be a better API for components like Component1
, preferably without modifying the props
. This could be done by lifting the state up into the component that renders <Draggable />
and <Component1 />
. This is what a ‘better API’ could look like:
import { forwardRef, useRef } from "react";
import Draggable, { useRichComponent } from "react-draggable";
import { italic } from "./App.module.css";
const Component1 = forwardRef((props, ref) => {
const { draggableProps, className } = props;
return (
<div {...draggableProps} ref={ref}>
<span>This should not be italic</span>
<br />
<span className={className}>This should be italic</span>
</div>
);
});
export default function App() {
const ref = useRef(null);
const { childProps, internalControl } = useRichComponent();
return (
<Draggable nodeRef={ref} internalControl={internalControl}>
<Component1 ref={ref} className={italic} draggableProps={childProps} />
</Draggable>
);
}
The above example uses a hook for the <Draggable />
to control the props of <Component1 />
without modifying the jsx element props. This is similar to Form.useForm()
in Ant Design.
This issue is related to #585 because I don’t think the solution to the issue is a good API, as it can cause problems demonstrated in the sandbox.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7
It doesn’t need the class.
Another way we could work around this would be to set the event handlers on the ref instead of the child, so the props don’t even need to be passed.
On Wed, Jul 21, 2021 at 10:25 PM Rajas Paranjpe @.***> wrote:
@STRML then I think my first solution would work best, with the
useRichComponent
hook. That would let React do the event handler stuff while still being flexible.