1
// utility hook
function useMouseOver() {
  const [mouseOver, setMouseOver] = useState(false);
  return {
    mouseOver,
    triggers: {
      onMouseEnter: () => setMouseOver(true),
      onMouseLeave: () => setMouseOver(false),
    },
  };
}

// mark component
function CommentHighlight({ attributes, children, ...props }) {
  const { mouseOver, triggers } = useMouseOver();
  return (
    <span
      {...attributes}
      {...triggers}
      style={{
        background: mouseOver ? yellow[600] : yellow[200],
        cursor: 'pointer',
      }}
    >
      {children}
    </span>
  );
}

Imagine 2 overlapped comments, they have different marks but rendered with the same component CommentHighlight:

-----
   ---------
aaaccbbbbbbb
  • a - has the mark from comment 1
  • b - has the mark from comment 2
  • c - has marks from comments 1 and 2

When I hover over aaa I need cc to change color too. But how?

The only guess I have is to track highlight state in redux (or similar) and update every comment component on state change. But this looks like overkill.

aiven
  • 3,775
  • 3
  • 27
  • 52

1 Answers1

0

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [back, setback] = React.useState(false);
  const changeback = value => {
    setback(value);
  };
  return (
    <React.Fragment>
      <CommentHighlight change={back} changeit={e => changeback(e)}>
        aaa
      </CommentHighlight>
      <CommentHighlight change={back} changeit={e => changeback(e)}>
        aaa
      </CommentHighlight>
    </React.Fragment>
  );
}
function useMouseOver(changeit) {
  const [mouseOver, setMouseOver] = React.useState(false);
  return {
    mouseOver,
    triggers: {
      onMouseEnter: () => {
        setMouseOver(true);
        changeit(true);
      },
      onMouseLeave: () => {
        setMouseOver(false);
        changeit(false);
      }
    }
  };
}

// mark component
function CommentHighlight({ attributes, children, ...props }) {
  const { mouseOver, triggers } = useMouseOver(props.changeit);
  return (
    <span
      {...attributes}
      {...triggers}
      style={{
        background: props.change ? "yellow" : "blue",
        cursor: "pointer"
      }}
    >
      {children}
    </span>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

i dont know if this the approach u looking for but here when u hover on first CommentHighlight the second will change color to and vice versa

adel
  • 3,436
  • 1
  • 7
  • 20
  • `CommentHighlight` components are govern by slate editor, I can't access them directly. And slatejs is rich text editor https://docs.slatejs.org/ – aiven Jun 28 '19 at 14:20