-1

So I have a regular page, I am working with next js. It looks like this:

"use client"

import SubjectInput from "../../../../components/subjectsInput"



export default function Page()
{
        let inputs = []
        for (let i = 0; i < numberOfInputsGiven; i++) {
            inputs.push(<SubjectInput key={i}/>)
        }

        return(
            <>
                <form>
                     <>
                        {inputs}
                     </>
                     <button type="submit">OK</button>
                </form>
            </>
        )
}

I use a component called "SubjectInput", to generate the input fields I need. Now, my question is, how can I access the value of the inputs that are in SubjectInput? Here is what SubjectInput looks like:

export default function SubjectInput(){
    return(
        <div>
            <div>
                <label>Name</label>
                <input type="text"  placeholder="Enter subject's name" required />
            </div>
            <div>
                <label>From</label>
                <input type="time" placeholder="Enter subject's starting time" required />
            </div>
            <div>
                <label>To</label>
                <input type="time" placeholder="Enter subject's ending time" required />
            </div>
        </div>
    )
}
Krizsa
  • 37
  • 4
  • Does this answer your question? [How to get the value of an input field using ReactJS?](https://stackoverflow.com/questions/36683770/how-to-get-the-value-of-an-input-field-using-reactjs) – Arkellys Nov 12 '22 at 12:49
  • No, because this is in another component. I want to find out if there is a way to get all of the inputs and access their value, while being in another component – Krizsa Nov 12 '22 at 12:55

1 Answers1

0

I would create a component that just holds one label and input, import it into the main page and change the values through props.

Main page

import Input from "./components/Input";

function App() {
  return (
    <div className="App">
      <form>
        <Input label="my text" type="text" value="hello" />
        <Input label="my number" type="number" value="123" />
        <Input type="submit" />
      </form>
    </div>
  );
}

export default App;

Input component

import React from "react";

const Input = (props) => {
  return (
    <div>
      <label>{props.label}</label>
      <input type={props.type} value={props.value} />
    </div>
  );
};

export default Input;
  • Okay, but how do I get the value of the inputs? Also, it will not be fixed, the user decides what the value will be. – Krizsa Nov 14 '22 at 09:29
  • Remove the default values of inputs from the main page (hello, 123), and on submission of the form save the value of the inputs in an object state. – Davide Coppola Nov 14 '22 at 09:51