Categories
React Tips

React Tips — Radio Buttons, Render HTML, and Initialize States

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.

Insert HTML with React

We can insert HTML in our React code.

To do that, we use the dangerouslySetInnerHTNL prop.

For instance, we can write:

render() {
  return (
    <div dangerouslySetInnerHTML={{ __html: someHtml }}></div>
    );
}

We pass in an object with the __html property to render raw HTML.

someHtml is a string with the HTML content.

Initialize State from Props in a React Component

We can initialize the state from props in a React component by setting this.state in the constructor.

For instance, we can write:

class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      x: props.initialX
    };
  }
  // ...
}

We get the props from the props parameter and set it as a property of this.state .

Call Change Event Listener After Pressing Enter Key

To call a onChange event handler after pressing the enter key, we can listen to the keydown event.

For instance, we can write:

class App extends React.Component {
  handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      console.log('entre pressed');
    }
  }

  render() {
    return <input type="text" onKeyDown={this.handleKeyDown} />
  }
}

We check the key property of the event object by comparing it to a string.

In a function component, we can write:

const App = () => {
  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      console.log('enter pressed')
    }
  }

  return <input type="text" onKeyDown={handleKeyDown} />
}

The handleKeyDown function is the same.

Specify a Port to Run a create-react-app Based Project

We can change the port that a create-react-app project listens to by setting the PORT environment variable.

For instance, we can add:

"start": "PORT=3006 react-scripts start"

into the scripts section of package.json .

in Linux or Mac OS.

In Windows, we can put:

"start": "set PORT=3006 && react-scripts start"

into the scripts section of package.json .

Use Radio Buttons in React

We can use a radio button with React by setting the value the onChange event listener on the radio button.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  handleChange = e => {
    const { name, value } = e.target;

    this.setState({
      [name]: value
    });
  };

  render() {
    return (
      <div>
        orange
        <input
          id="orange"
          value="orange"
          name="fruit"
          type="radio"
          onChange={this.handleChange}
        />
        grape
        <input
          id="grape"
          value="grape"
          name="fruit"
          type="radio"
          onChange={this.handleChange}
        />
        apple
        <input
          id="apple"
          value="apple"
          name="fruit"
          type="radio"
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

We created multiple radio buttons with the same name attribute.

This way, we can choose one of them out of all the buttons.

In the handleChange method, we call setState with the e.target.name as the key and e.target.value as the value.

This sets the state with the name of the radio buttons which is fruit and the value will be the value of the value attribute.

With function components, we write:

const useInput = (initialValue) => {
  const [value, setValue] = useState(initialValue);

  function handleChange(e){
    setValue(e.target.value);
  }

  return [value, handleChange];
}

function App() {
  const [fruit, setFruit] = useInput("");

  return (
    <form>
      <div>
        <input type="radio" id='apple' value='apple'
        checked={fruit === 'apple'} onChange={setFruit}/>
        <label>apple</label>
      </div>
      <div>
        <input type="radio" id='orange' value='orange'
        checked={fruit === 'orange'} onChange={setFruit}/>
        <label>orange</label>
       </div>
       <div>
        <input type="radio" id='grape' value='grape'
        checked={fruit === 'grape'} onChange={setFruit}/>
        <label>grape</label>
       </div>
     </form>
  )
}

We created the radio buttons the same way, but we created our own useInput hook to make the change handling logic reusable.

In the hook, we used the useState method to set the state.

Then we return both the value , which always have the latest value, and handleChange , which has our event handler function.

Then we used the returned values of the useInput hook in our App component.

We passed the setFruit handler function which is returned as the 2nd entry of the array to the onChange prop.

Then the value will be set when we click the buttons.

We also have the checked prop to render the buttons with the proper checked values.

Conclusion

We can set radio buttons values with the handler function we pass into the onChange prop.

We’ve to set their name attributes to be the same.

To render raw HTML, we pass an object into the dangerouslySetInnerHTML prop.

Also, we can initialize states with props.

The port to run our create-react-app project can change.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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