Open In App

How to add code input in React JS?

Improve
Improve
Like Article
Like
Save
Share
Report

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

Approach to add code input:

To incorporate our code input, we’ll utilize the react-code-input package. This package facilitates the seamless integration of code input into our application. Begin by installing the react-code-input package, followed by the addition of a code input section on our homepage.

Steps to create React Application And Installing Module:

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd foldername

Step 3: Install the required package

npm i react-code-input

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-code-input": "^3.10.1",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

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.

Example: 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>
    );
}


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

npm start

Output:



Last Updated : 25 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads