Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active September 20, 2023 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/061f1202ab12b3cafd48bf6c1383402a to your computer and use it in GitHub Desktop.
Save Noitidart/061f1202ab12b3cafd48bf6c1383402a to your computer and use it in GitHub Desktop.
function useRenderCounter(label) {
const ref = React.useRef();
React.useEffect(() => {
ref.current.textContent = [
parseInt(ref.current.textContent || "0", 10) + 1,
label
]
.filter(Boolean)
.join(" - ");
});
return (
<span
style={{
backgroundColor: "#ccc",
borderRadius: 4,
padding: "2px 4px",
fontSize: "0.8rem",
margin: "0 6px",
display: "inline-block"
}}
ref={ref}
/>
);
}
@Noitidart
Copy link
Author

Noitidart commented May 10, 2021

React Native

function useRenderCounter(label = '') {
  const inputRef = React.useRef();
  const savedCount = React.useRef(0);
  React.useEffect(() => {
    savedCount.current++;
    inputRef.current?.setNativeProps({
      text: label + (label ? ': ' : '') + savedCount.current.toString(),
    });
  });
  return (
    <TextInput
      style={{
        alignSelf: 'flex-start',
        backgroundColor: '#ccc',
        borderRadius: 4,
        paddingHorizontal: 4,
        paddingVertical: 2,
        marginHorizontal: 6,
        fontSize: 12,
        // position: 'absolute',
        transform: [{ translateX: -4 }, { translateY: -4 }]
      }}
      pointerEvents="none"
      defaultValue={savedCount.current.toString()}
      ref={inputRef}
    />
  );
}

@Noitidart
Copy link
Author

HTML version without useEffect:

function RenderCounter(props: { label?: string } ) {
  const savedCount = useRef(0);

  return (
    <span
      style={{
        backgroundColor: "#ccc",
        borderRadius: 4,
        padding: "2px 4px",
        fontSize: "0.8rem",
        margin: "0 6px",
        display: "inline-block"
      }}
    >
      {Boolean(label) ? `${label}: ` : ''}{++savedCount.current}
    </span>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment