skip to Main Content

I want to implement this feature in my app and I would appreciate any tip. So if the user clicks on the Use As Display Name checkbox, I want the value of the App name to be the same as the Display name, like a copy and paste function.

enter image description here

import { Box, Checkbox, FormControl, FormLabel, Flex, Input } from "@chakra-ui/react"
import { useState } from "react"

export const CreateAnApp = (props) => {

 const [formData, setFormData] = useState({
  name: "",
  displayName: "",
  ,
 });
 const { name, displayName } = formData;

 const onChange = (e) => {
  setFormData((prevState) => ({
    ...prevState,
    [e.target.name]: e.target.value,
  }));
 };

 return ( 
 <Flex mt = {6}>
  <Box>
   <FormControl>
    <FormLabel fontSize = "sm" fontWeight = "semibold">
     App Name 
    </FormLabel>
    <Input fontSize = "14" width = {{ sm: "165px", md: "225px"}} 
      name="name" 
      type = "text" 
      value = {name} 
      onChange = {onChange}
     />
   </FormControl>
    <Checkbox size = 'sm'>Use as display name</Checkbox>
  /Box>
  
 <Box ml = {2}>
  <FormControl>
   <FormLabel fontSize = "sm" fontWeight = "semibold">
    Display Name
   </FormLabel>
   <Input fontSize = "14" width = {{sm: "165px", md: "225px"}} 
     name="displayName"
     type = "text"
     value = {displayName}
     onChange = {onChange}
   />
  </FormControl>
 </Box>
 </Flex>
 )
 }

2

Answers


  1. I don’t have much React knowledge. But this is the logic which can be applied. Try it:

    <input type="text" placeholder="App Name" class="app-name">
    <input type="text" placeholder="Display Name" class="display-name">
      
    <br>
      
    <input type="checkbox" id="myCheckBox" onchange="myFunction()">
    <label for="myCheckBox">Use as Display Name</label>
    
    <script>
    const appName = document.querySelector('.app-name');
    const displayName = document.querySelector('.display-name');
    
    function myFunction(){
      if(document.querySelector('#myCheckBox').checked){
        appName.value = displayName.value;
      }
    }
    </script>
    Login or Signup to reply.
  2. Add a onChange handler on the Checkbox:

    <Checkbox size = 'sm' onChange={onCheckBoxChange}>Use as display name</Checkbox>
    

    Then, onChange, copy the name from prevState to displayName if the checkbox is checked:

    const onCheckBoxChange = (event) => {
        if (event.target.checked) {
            setFormData((prevState) => ({
                ...prevState,
                displayName: prevState.name,
            }));
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search