SBUK-Tech
SBUK-Tech

Reputation: 1327

How to adjust the onClick event of react.children when child is a react component not a DOM element

When creating a component that uses the children prop I would like to adjust its onclick event. This is easy if the child is a DOM element e.g. a Div but if it is a react component I can only edit the component props not the props of the resulting DOM element. Edit: child component should be abstract and is not accessible for editing.

The following works for a DOM element:

export const Wrapper = ({ children }) => {
  const handleOnClick = () => {};
  return (
    React.cloneElement(children, { ...children.props, onClick: handleOnClick })
  )
}

const App = () => {
  return (
    <Wrapper>
      <div /> // This div has a onclick event injected by wrapper
    </Wrapper>
  )
}

The following does not work

export const Wrapper = ({ children }) => {
  const handleOnClick = () => {};
  return (
    React.cloneElement(children, { ...children.props, onClick: handleOnClick })
  )
}

const InnerWrap = () => {
  return (
    <div /> // This div does not get onClick injected
  )
}

const App = () => {
  return (
    <Wrapper>
      <InnerWrap />
    </Wrapper>
  )
}

I have also tried with Refs but can't work out a way to apply to event to the ref

...
const childRef = useRef(null);
useLayoutEffect(() => {
  //childRef.current is Null!
  childRef.current.addEventListener('onClick', handleOnClick);
}, [childRef]);

React.cloneElement(children, { ref: childRef })

...

Upvotes: 1

Views: 640

Answers (1)

Giedrius Vičkus
Giedrius Vičkus

Reputation: 106

Maybe try something like this?

const InnerWrap = ({props}) => {
  return (
    <div {...props} />
  )
}

Upvotes: 0

Related Questions