Skip to content
Related Articles

Related Articles

How to add code input in React.js ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 28 Dec, 2021

In this article, we are going to learn how we can add Code Input in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.

Approach: To add our code input we are going to use the react-code-input package. The react-code-input package helps us to integrate the code input in our app. So first, we will install the react-code-input package and then we will add a code input on our homepage.

Create ReactJs Application: You can create a new ReactJs project using the below command:

npx create-react-app gfg

Install the required package: Now we will install the react-code-input package using the below command:

npm i react-code-input

Project Structure: It will look like this.

Adding the Code Input: After installing the package we can easily add a code input on any page in our app. For this example, we are going to add a code input to our homepage.

Add the below content in the App.js file:

Javascript




import React from 'react';
import ReactCodeInput from 'react-code-input';
  
export default function GfgInput() {
  const props = {
    inputStyle: {
      fontFamily: 'monospace',
      margin:  '4px',
      MozAppearance: 'textfield',
      width: '40px',
      borderRadius: '3px',
      fontSize: '14px',
      height: '26px',
      paddingLeft: '7px',
      backgroundColor: 'white',
      color: 'lightskyblue',
      border: '1px solid lightskyblue'
    },
    inputStyleInvalid: {
      fontFamily: 'monospace',
      margin:  '4px',
      MozAppearance: 'textfield',
      width: '40px',
      borderRadius: '3px',
      fontSize: '14px',
      height: '26px',
      paddingLeft: '7px',
      backgroundColor: 'black',
      color: 'red',
      border: '1px solid red'
    }
  }
  
  return (
    <div>
      <h2>GeeksforGeeks React - Code Input</h2>
      <ReactCodeInput type='number' fields={6} {...props}/>
    </div>
  );
}

Explanation: In the above example first, we are importing the ReactCodeInput component and adding some styling in a new variable named props. After that, we are adding our code input using the installed package.

Steps to run the application: Run the below command in the terminal to run the app.

npm start

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!