Home > Blockchain >  how can I display the current ref value in my button?
how can I display the current ref value in my button?

Time:10-28

I use useRef instead of useState. But my btn name not changing. Why ?

  const data = useRef(null);

  const handlePressCategory = (category: Categories) => {
    data.current = category;
    modalCategoriesRef.current?.close();
  }

        <Pressable style={[ButtonStyles.full_without, s.btn]} onPress={handleOpenModalCategories}>
          <Text style={s.btnText}>{ data.current === null ? 'Kategorie auswählen' : data.current}</Text>
        </Pressable>

I am very thankful for your help and answers. I dont know why its not displaying

CodePudding user response:

Changing data with useRef doesn't trigger React to re-render your views. Think about it like some field in class that you can change without any reaction.

https://reactjs.org/docs/hooks-reference.html#useref

If you need re-render view when your ref have changes, just use useState. It's designed specially for it

Otherwise, if it's not possible, you can write some useForceRerender hook that will invoke render of your component. Something like that:

export const useForceRerender = () => React.useReducer((x) => x   1, 0)[1];

const App = () => {
  const data = useRef(null);
  const forceRerender = useForceRerender();

  const handlePressCategory = (category: Categories) => {
    data.current = category;
    modalCategoriesRef.current?.close();
    
    forceRerender(); // <-- here
  }

  return (
    <Pressable style={[ButtonStyles.full_without, s.btn]} onPress={handleOpenModalCategories}>
      <Text style={s.btnText}>{ data.current === null ? 'Kategorie auswählen' : data.current}</Text>
    </Pressable>
  )
}

  • Related