LayTexas
LayTexas

Reputation: 645

this.refs x useRef (Is there any similarity?)

I'm trying to use a library that uses this.ref, but I have to pass it to hooks. I'm not getting it.

Original code:

      import ViewShot from "react-native-view-shot";

      class ExampleCaptureOnMountManually extends Component {
        componentDidMount () {
          this.refs.viewShot.capture().then(uri => {
            console.log("do something with ", uri);
          });
        }
        render() {
          return (
            <ViewShot ref="viewShot" options={{ format: "jpg", quality: 0.9 }}>
              <Text>...Something to rasterize...</Text>
            </ViewShot>
          );
        }
      }

My hook code:

    export default function screenshot() {
      const refs = useRef();

      refs.viewShot.capture().then(uri => {
        console.log('do something with ', uri);
      });

      return (
        <View style={styles.container}>
          <View style={styles.header} />
          <ViewShot ref="viewShot" options={{format: 'jpg', quality: 0.9}}>
            <View>
              <Text>Hello World</Text>
            </View>
          </ViewShot>

          <View style={styles.footer}>
            <Button title="print" onPress={onCapture} />
          </View>
        </View>
      );
    }

Link Lib: https://github.com/gre/react-native-view-shot

Upvotes: 0

Views: 467

Answers (1)

acdcjunior
acdcjunior

Reputation: 135792

With useRef(), you don't do const refs = useRef();, you declare the ref:

const viewShot = useRef();

And then pass it in the ref attribute:

<ViewShot ref={viewShot} ...

You should now use it as viewShot.current.

Nevertheless, since your original code executed in componentDidMount, now you should also employ useEffect (notice the addition of .current):

useEffect(() => {
  viewShot.current.capture().then(uri => {
    console.log('do something with ', uri);
  });
}, [])

Therefore:

export default function screenshot() {
  const viewShot = useRef();

  useEffect(() => {
    viewShot.current.capture().then(uri => {
      console.log('do something with ', uri);
    });
  }, [])

  return (
    <View style={styles.container}>
      <View style={styles.header} />
      <ViewShot ref={viewShot} options={{format: 'jpg', quality: 0.9}}>
        <View>
          <Text>Hello World</Text>
        </View>
      </ViewShot>

      <View style={styles.footer}>
        <Button title="print" onPress={onCapture} />
      </View>
    </View>
  );
}

Upvotes: 3

Related Questions