React references — what is this.refs — by Steven Lacerda (Morgan Hill, CA)

Steven Lacerda
1 min readAug 15, 2018

--

I learned something new today, something that totally changed my understanding of React. The true nature of refs!!!

I found myself using jQuery at times, which is totally wrong. So, I started doing some research and found out that this.refs.myComponent gets the instance of that object and its associated properties and methods.

Thus, I can now call the instances methods from wherever I obtain the the instance. For example,

Parent class:

Main = React.createClass({  handleShow() {    this.refs.wrapper.show();  },  render() {    <Wrapper ref=”wrapper”>      // some stuff here    </Wrapper>  }});

Child Class:

Wrapper = React.createClass({  getInitialState() {    isShown: false,  },  show() {    this.setState({ isShown: !this.state.isShown });  }  render() {    <div className={ this.state.isShown ? “” : “hidden” }>      // stuff here    </div>  }});

As you can hopefully see from the example, you’re accessing the child class using this.refs.wrapper, and using its .show() method.

Maybe this is totally self-explanatory to most, but it was an aha moment for me. Hope you learned something also.

As always, don’t be a prisoner to your code, master it!!!

Solving a problem is as good as those sexual feelings…sometimes, okay, maybe not. Straight from Morgan Hill, CA. Good luck!

— by Steven Lacerda

--

--

Steven Lacerda
Steven Lacerda

Written by Steven Lacerda

Steve Lacerda is a software engineer specializing in web development. His favorite 80’s song is Let’s Put the X in Sex by Kiss.

No responses yet