Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="app"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                // ref element
function SingleRef() {
  // the name input value
  const [name, setName] = React.useState("Codemzy");
  // the input ref
  const inputRef = React.useRef(null);
  
  // to focus the input
  function handleClick() {
    inputRef.current.focus();
  };
  
  return (
    <div className="py-10">
      <h2 className="text-lg font-bold">User</h2>
      <p className="text-gray-700 pb-4">A single input with a single ref.</p>
      <label htmlFor="name-input">Name</label>
      <input ref={inputRef} id="name-input" name="name" value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={handleClick}>Focus Me</button>
    </div>
  );
}

// dynamic ref array
function RefArray() {
  // the team input values
  const [team, setTeam] = React.useState([ "" ]);
  // the input refs array
  const inputRefs = React.useRef([]);
  
  // focus on last team member when team state changes
  React.useEffect(() => {
    inputRefs.current[team.length-1].focus();
  }, [team]);
  
  // add a team member
  function addMember() {
    setTeam([ ...team, ""]);
  };
  
  // update a team member
  function updateMember(index, value) {
    setTeam([ ...team.slice(0, index), value, ...team.slice(index+1)]);
  };
  
  // to focus the input
  function handleClick(element) {
    inputRefs.current[element].focus();
  };
  
  return (
    <div className="py-10">
      <h2 className="text-lg font-bold">Team</h2>
      <p className="text-gray-700 pb-4">Dynamic inputs with an array ref.</p>
      {team.map((member, i) => {
        return (
          <div key={i}>
            <label htmlFor={`input-array-${i+1}`}>Member {i+1}</label>
            <input ref={(element) => inputRefs.current[i] = element} id={`input-array-${i+1}`} value={team[i]} onChange={(e) => updateMember(i, e.target.value)} />
            <button onClick={() => handleClick(i)}>Focus Me</button>
          </div>
        );
      })}
      <div className="my-5 -mx-1">
        <button onClick={addMember}>Add Member</button>
      </div>
    </div>
  );
};

// generate a unique id
const getId = function({ length = 6, existing = [] }) {
  // create a random id
  function randomId() {
    return Math.random().toString(36).substring(2, length+2);
  };
  // check if id already exists
  function checkId(id, existing = []) {
    let match = existing.find(function(item) {
      return item === id;
    });
    return match ? false : true;
  };
  // create a new unique id
  const limit = 100; // max tries to create unique id
  let attempts = 0; // how many attempts
  let id = false;
  while(!id && attempts < limit) {
    id = randomId(length); // create id
    if(!checkId(id, existing)) { // check unique
      id = false; // reset id
      attempts++; // record failed attempt
    }
  }
  return id; // the id or false if did not get unique after max attempts
};

// dynamic ref object
function RefObject() {
  // the team input values
  const [team, setTeam] = React.useState([ { id: getId({}), value: "" } ]);
  // for focus on an Id
  const [focusId, setFocusId] = React.useState(false);
  // the input refs object
  const inputRefs = React.useRef({});
  
  // focus on a team member
  React.useEffect(() => {
    if (focusId) {
      inputRefs.current[focusId].focus();
      setFocusId(false);
    }
  }, [focusId]);
  
  // add a team member - now adds a unique id
  function addMember() {
    let id = getId({ existing: team.map(member => member.id) }); // new unique id
    setTeam([ ...team, { id, value: "" }]);
    setFocusId(id); // to trigger focusing the new member once added to state
  };
  
  // update a team member - now takes unique id
  function updateMember(id, value) {
    setTeam([ ...team.map((member) => {
      if (member.id === id) {
        return {...member, value};
      }
      return member;
    })]);
  };
  
  // remove a team member - now takes unique id
  function removeMember(id) {
    setTeam(team.filter((member) => member.id !== id));
  };
  
  // to focus the input - now takes unique id
  function handleClick(id) {
    inputRefs.current[id].focus();
  };
  
  return (
    <div className="py-10">
      <h2 className="text-lg font-bold">Team</h2>
      <p className="text-gray-700 pb-4">Dynamic inputs with an object ref.</p>
      {team.map((member, i) => {
        return (
          <div key={member.id}>
            <label htmlFor={`input-array-${member.id}`}>Member {i+1}</label>
            <input ref={(element) => inputRefs.current[member.id] = element} id={`input-array-${member.id}`} value={member.value} onChange={(e) => updateMember(member.id, e.target.value)} onKeyDown={(e) => { e.key === "Backspace" && !e.target.value && removeMember(member.id) }} />
            <button onClick={() => handleClick(member.id)}>Focus Me</button>
          </div>
        );
      })}
      <div className="my-5 -mx-1">
        <button onClick={addMember}>Add Member</button>
      </div>
    </div>
  );
};

// app component
function App() {
  return (
    <div className="p-10">
      <h1 className="font-semibold text-3xl py-2">ReactJS useRef</h1>
      <p>With Tailwind CSS to make things look pretty!</p>
      <SingleRef />
      <RefArray />
      <RefObject />
     </div>
    )
}


// ========================================

ReactDOM.render(
  <App />,
  document.getElementById('app')
);
              
            
!
999px

Console