Nilesh
Nilesh

Reputation: 618

how to set props values of controls in react js

I am new to react. I have almost 15 input controls on UI. Some are dropdowns, some are textboxes, couple of calender controls and radio buttons. I want to retrive all values before submitting a page. Do I need to define 15 props in state object of component for 15 inputs? is there any way to have it in one object. Also how to set the values of each control. For example for textbox I know, its like

<input type="text" name="username" className="form-control" id="exampleInput" value={this.props.name} onChange={this.handleChange} placeholder="Enter name"></input>

How to handle same for dropdown,calender and radio buttton. Thanks in advance.

Upvotes: 0

Views: 964

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074575

Normally, these wouldn't be props, they'd be state (which is different). You can use objects in state. If you're doing a class-based component (class YourComponent extends React.Component), state is always an object you create in the constructor and update with setState. If you're doing this in a function component, typically you use separate state variables for each thing (const [name, setName] = useState("");), but you can use an object if you prefer. There's more about state in the documentation.

That said, if you only want the values when you take an action, you could make the inputs "uncontrolled."

Here's a three-input example using a class component:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            firstName: "",
            lastName: "",
            about: ""
        };
        this.handleChange = this.handleChange.bind(this);
    }
    
    handleChange({target: {name, value}}) {
        this.setState({[name]: value});
    }
    
    render() {
        const {firstName, lastName, about} = this.state;
        const {handleChange} = this;
        return <div>
            <div>
                <label>
                    First name:
                    <br/>
                    <input type="text" value={firstName} name="firstName" onChange={handleChange} />
                </label>
            </div>
            <div>
                <label>
                    Last name:
                    <br/>
                    <input type="text" value={lastName} name="lastName" onChange={handleChange} />
                </label>
            </div>
            <div>
                <label>
                    About you:
                    <br />
                    <textarea value={about} name="about" onChange={handleChange} />
                </label>
            </div>
            <div>{firstName} {lastName} {(firstName || lastName) && about ? "-" : ""} {about}</div>
        </div>;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

Here's one using a functional component with discrete state items (usually best):

const { useState } = React;

const Example = () => {
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [about, setAbout] = useState("");
    
    // There's are lots of ways to do this part, this is just one of them
    const handleChange = ({target: {name, value}}) => {
        switch (name) {
            case "firstName":
                setFirstName(value);
                break;
            case "lastName":
                setLastName(value);
                break;
            case "about":
                setAbout(value);
                break;
        }
    };

    return <div>
        <div>
            <label>
                First name:
                <br/>
                <input type="text" value={firstName} name="firstName" onChange={handleChange} />
            </label>
        </div>
        <div>
            <label>
                Last name:
                <br/>
                <input type="text" value={lastName} name="lastName" onChange={handleChange} />
            </label>
        </div>
        <div>
            <label>
                About you:
                <br />
                <textarea value={about} name="about" onChange={handleChange} />
            </label>
        </div>
        <div>{firstName} {lastName} {(firstName || lastName) && about ? "-" : ""} {about}</div>
    </div>;
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

Here's one using a functional component with an object in state:

const { useState } = React;

const Example = () => {
    const [data, setData] = useState({firstName: "", lastName: "", about: ""});
    
    const handleChange = ({target: {name, value}}) => {
        setData(current => ({...current, [name]: value}));
    };

    const {firstName, lastName, about} = data;
    return <div>
        <div>
            <label>
                First name:
                <br/>
                <input type="text" value={firstName} name="firstName" onChange={handleChange} />
            </label>
        </div>
        <div>
            <label>
                Last name:
                <br/>
                <input type="text" value={lastName} name="lastName" onChange={handleChange} />
            </label>
        </div>
        <div>
            <label>
                About you:
                <br />
                <textarea value={about} name="about" onChange={handleChange} />
            </label>
        </div>
        <div>{firstName} {lastName} {(firstName || lastName) && about ? "-" : ""} {about}</div>
    </div>;
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

Upvotes: 1

iamhuynq
iamhuynq

Reputation: 5539

You can set name for input and update state base on event.target.name and event.target.value

constructor() {
    super();
    this.state = {
      text: "",
      select: "",
      radio: ""
    };
  }
  handeInput = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <input
          onChange={this.handeInput}
          type="input"
          name="text"
          value={this.state.text}
        />
        <select
          name="select"
          onChange={this.handeInput}
          value={this.state.select}
        >
          <option value="option1">option1</option>
          <option value="option2">option2</option>
        </select>
        <input
          type="radio"
          name="radio"
          value="Option1"
          checked={this.state.radio === "Option1"}
          onChange={this.handeInput}
        />
        Option1
        <input
          type="radio"
          name="radio"
          value="Option2"
          checked={this.state.radio === "Option2"}
          onChange={this.handeInput}
        />
        Option2
      </div>
    );
  }

You can check here CodeSandBox Hope it helps

Upvotes: 0

Sam
Sam

Reputation: 1239

Here is the sample code, I used in my application.

class CreditCardForm extends React.Component {
      constructor() {
        super()

        this.state = {
          name: '',
          address: '',
          ccNumber: ''
        }
      }

      handleChange(e) {
        // If you are using babel, you can use ES 6 dictionary syntax
        // let change = { [e.target.name] = e.target.value }
        let change = {}
        change[e.target.name] = e.target.value
        this.setState(change)
      }

      render() {
        return (
          <form>
            <h2>Enter your credit card details</h2>

            <label>
              Full Name
              <input type="name" onChange={(e)=>this.handleChange(e)} value={this.state.name} />
            </label>

            <label>
              Home address
              <input type="address" onChange={(e)=>this.handleChange(e)} value={this.state.address} />
            </label>

            <label>
              Credit card number
              <input type="ccNumber" onChange={(e)=>this.handleChange(e)} maxlength="16" value={this.state.ccNumber} />
            </label>

            <button type="submit">Pay now</button>
          </form>
        )
      }
    }

Upvotes: 0

Related Questions