Categories
React Tips

React Tips — colspan, Active Links, API Calls, and Multiple Refs

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Make API Call with Hooks in React

We can make API calls in the useEffect hook.

For instance, we can write:

function User() {
  const [firstName, setFirstName] = React.useState();

  React.useEffect(() => {
    fetch('https://randomuser.me/api/')
      .then(results => results.json())
      .then(data => {
        const {name} = data.results[0];
        setFirstName(name.first);
      });
  }, []);

  return (
    <div>
      Name: {firstName}
    </div>
  );
}

We get call fetch in the useEffect callback to get the data.

Then we set the firstNam,e state with setFirstName .

We pass in an empty array to the 2nd argument of useEffect to make the callback run on component mount only.

Finally, we render the firstName in the return statement.

If we want to load data when props change, then we pass the prop into the array in the 2nd argument.

React colspan

We can add the colspan attribute with the colSpan prop.

For instance, we can write:

<td colSpan={6} />

How can I Style Active Link in React Router

We can style an active link with React Router with the NavLink component.

For instance, we can write:

<NavLink to="/profile" activeClassName="selected">
  profile
</NavLink>

The activeClassName lets us set the class name for the when the link is active.

There’s also the activeStyle prop to let us pass in styles for active links.

For instance, we can write:

<NavLink
  to="/profile"
  activeStyle={{
    fontWeight: "bold",
    color: "green"
  }}
>
  profile
</NavLink>

We pass in an object with the styles we want to apply.

The CSS property names are all changed to camel case.

Trigger onChange if Input Value is Changing by State

We can set the state in the handler.

And we can trigger the event we want with the Event constructor.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      value: 'foo'
    }
  }

  handleChange (e) {
    console.log('changed')
  }

  handleClick () {
    this.setState({ value: 'something' })
    const event = new Event('input', { bubbles: true });
    this.input.dispatchEvent(event);
  }
  render () {
    return (
      <div>
        <input readOnly value={this.state.value} onChange={(e) => this.handleChange(e)} ref={(input)=> this.input = input} />
        <button onClick={this.handleClick.bind(this)}>update input</button>
      </div>
    )
  }
}

We have a button that has a click handler attached to it.

That’s the handleClick method.

Then we call setState on it to set the value state.

We then create an input event and make it bubble.

Then trigger an event on the input with dispatchEvent .

Add Google Sign-in Button with React

We can add a Google sign-in button within a React component by loading the google sign-in code in when the component loads.

For instance, we can write:

componentDidMount() {
  gapi.signin2.render('g-signin2', {
    'scope': 'https://www.googleapis.com/auth/plus.login',
    'width': 200,
    'height': 50,
    'longtitle': true,
    'theme': 'dark',
    'onsuccess': this. onSignIn
  });
}

We call the gapi.signin2.render method that comes with the API.

It’s added to componentDidMount so that it runs when the component loads.

With function components, we can write:

useEffect(() => {
  window.gapi.signin2.render('g-signin2', {
    'scope': 'https://www.googleapis.com/auth/plus.login',
    'width': 200,
    'height': 50,
    'longtitle': true,
    'theme': 'dark',
    'onsuccess': onSignIn
  })
}, [])

We call the same method within the useEffect callback.

The empty array in the 2nd argument ensures that it loads only when the component loads.

Use Multiple refs for an Array of Elements with Hooks

We can create multiple refs within the useEffect callback.

For instance, we can write:

const List = ({ arr }) => {
  const arrLength = arr.length;
  const [elRefs, setElRefs] = React.useState([]);

  React.useEffect(() => {
    setElRefs(elRefs => (
      Array(arrLength).fill().map((_, i) => elRefs[i] || ReactcreateRef())
    ));
  }, [arrLength]);

  return (
    <div>
      {arr.map((el, i) => (
        <div ref={elRefs[i]}>...</div>
      ))}
    </div>
  );
}

We have the useState hook to create an array.

Then we call the setElRefs returned from useState to and call fill to create an array with empty slots.

Then we call map to create the refs or return an existing one.

Then we pass the ref by index to the div.

Conclusion

We can add multiple refs by mapping them to the array.

Also, we can make API calls in the useEffect callback.

NavLink s can be styled when they’re active.

Leave a Reply

Your email address will not be published. Required fields are marked *