Abhisar2006
Abhisar2006

Reputation: 17

How Do I replace UUID with string with input box?

So I am trying to learn reactJS and am stuck in one place.

In the code below:

   import React from "react";
import { v1 as uuid } from "uuid";

const CreateRoom = (props) => {
    function create() {
        const id = uuid();
        props.history.push(`/room/${id}`);
        console.log(id);
    }

    return ([
      
        <button onClick={create}>Create room</button>
    ]);
};

export default CreateRoom;

I am getting a basic button which is creating a room with a random url.(Such is UUID)

How do I insert a textbox(Input) where the user can enter the room name. I tried regular methods by creating a new file called id.js and creating an ID function but to no avail.

What am I doing wrong? You can check out this use case by visiting https://vidci-vid.herokuapp.com/

Upvotes: 0

Views: 440

Answers (2)

Drew Reese
Drew Reese

Reputation: 202836

window.prompt could be a simple, easy replacement choice.

The Window.prompt() displays a dialog with an optional message prompting the user to input some text.

const CreateRoom = (props) => {
    function create() {
      const id = window.prompt("Enter room id");
      props.history.push(`/room/${id}`);
      console.log(id);
    }

    return ([
      
        <button onClick={create}>Create room</button>
    ]);
};

Edit how-do-i-replace-uuid-with-string-with-input-box

Sandbox code

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import "./styles.css";

const CreateRoom = ({ history }) => {
  const create = () => {
    const id = window.prompt("Enter room id");
    history.push(`/room/${id}`);
    console.log(id);
  }

  return <button onClick={create}>Create room</button>;
};

const Room = ({ history, match }) => (
  <div>
    Room: {match.params.id}
    <button type="button" onClick={history.goBack}>
      Back to CreateRoom
    </button>
  </div>
);

export default function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/room/:id" component={Room} />
          <Route path="/" component={CreateRoom} />
        </Switch>
      </Router>
    </div>
  );
}

Upvotes: 1

ashishmishra
ashishmishra

Reputation: 389

one method is to create a local state variable and assign input to that variable like this:

  var [Text, getInput] = useState(''); // declaring state variable

// assigning input to that state
                <TextField
                  value={Text}
                  onChange={e => getInput(e.target.value)}
                />
                <ButtonBase
                  onClick={create}
                >Create Room
                </ButtonBase>

And if you want to clear the input in UI after submit, just do like this in your input handling function, once your processing of input is done:

getInput('')

Upvotes: 1

Related Questions