DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info on

React Tips — Context, Hover, and Input Fields

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

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.

Get the Value of an Input Field Using React

To get the value of an input field with React, first, we set the inputted value to a state.

Then we get the latest value from the state.

For instance, we can write:

class InputForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      val: ''
    };
  }

  render() {
    return (
      //...
      <input value={this.state.val} onChange={evt => this.updateInputValue(evt)}/>
      //...
    );
  },

  updateInputValue(evt) {
    this.setState({
      val: evt.target.value
    });
  }
});

Enter fullscreen mode Exit fullscreen mode

We created the updateInputValue method which calls setState to set the value of the input field as the value of the val state.

Then we pass that into the onChange prop.

The value prop has the this.state.val which we set.

With function components, we use the useState hook to set the value and retrieve it.

For instance, we can write:

import { useState } from 'react';

function InputForm() {
  const [val, setVal] = useState('');

  return (
    <div>
      <input value={val} onInput={e => setVal(e.target.value)}/>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

We called the useState function with the initial value of the input.

Then we passed a function to the onInput prop to run it to set the value to the val state when whenever something is entered.

Then we get the latest inputted value with the val variable.

Pass Form Element State to Sibling or Parent Elements

To most versatile way to pass data between element is to us the context APU.

For instance, we can write:

import React, { useState, useContext } from "react";
import ReactDOM from "react-dom";

const Context = React.createContext(null);

const initialAppState = {};

function App() {
  const [appState, updateAppState] = useState(initialAppState);

return (
    <div>
      <Context.Provider value={{ appState, updateAppState }}>
        <Comment />
      </Context.Provider>
    </div>
  );
}

function Comment() {
  const { appState, updateAppState } = useContext(Context);

  function handleCommentChange(e) {
    updateAppState({ ...appState, comment: e.target.value });
  }

  return (
    <div className="book">
      <input
        type="text"
        value={appState.comment}
        onChange={handleCommentChange}
      />
      <br />
      <div>
        <pre>{JSON.stringify(appState, null, 2)}</pre>
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

We created the context with the React.createContext method to create the context.

Then in App, we add the Context.Provider so that all the child elements can have access to the context.

Then we created the Comment component which calls the useContext hook to use our Context context. In the component, we have an input to change the appState as we enter something. This will be reflected in all components that use the context.

We can see what we entered in the stringified JSON that’s below the input.

How to Implement a:hover with Inline CSS Styles in React

We can listen to the mouseenter and mouseleave events to create an effect for hover.

For instance, we can write:

class Foo extends React.Component {
  constructor() {
    this.state = { hover: false };
  }

  toggleHover(){
    this.setState({ hover: !this.state.hover })
  },

  render() {
    let linkStyle;
    if (this.state.hover) {
      linkStyle = { backgroundColor: 'red' }
    } else {
      linkStyle = { backgroundColor: 'green' }
    }
    return(
      <div>
        <a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
  }
}

Enter fullscreen mode Exit fullscreen mode

We created our component by adding a a element that listens to the mouseenter and mouseleave events by passing methods to the onMpuseEnter and onMouseLeave props.

The toggleHover method toggles the hover state between true and false .

Then in the render method, we set the backgroundColor property depending on the truth value of the hover state.

Also, we can use the style-it library which lets us embed CSS with pseudoclasses into our React components.

We install it by running:

npm install style-it --save

Enter fullscreen mode Exit fullscreen mode

Then we can write:

import React from 'react';
import Style from 'style-it';

class Foo extends React.Component {
  render() {
    return Style.it(`
      p:hover {
        color: red;
      }
    `,
      <p>hover me</p>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Then we use the Style.it tag from the style-it library to let us set the hover state of our element.

We can also use the Style component to do the same thing.

For instance, we can write:

import React from 'react';
import Style from 'style-it';

class Foo extends React.Component {
  render() {
    return (
      <Style>
        {`
          p:hover {
            color: red;
          }
        `}
        <p>hover me</p>
      </Style>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

We use the Style component and embed our CSS with the hover pseudoclass in the string.

Then we’ll see a color change when we hover over the p element.

Conclusion

We can use a library or plain JavaScript to create a hover effect.

There are various ways to get input field values and pass data around multiple components.

The post React Tips — Context, Hover, and Input Fields appeared first on The Web Dev.

Top comments (0)