Home > Software engineering >  How do I pass input values to a new div in React?
How do I pass input values to a new div in React?

Time:01-08

I'm working on a CV Generator and I don't know how to properly append the school and field of study values to a new div inside React.

Using the onSubmit function I'm able to get the values after filling them out and clicking save, but I can't figure out where to go from here.

Update

What I want to do is take the values from the input and create a new div above the form that displays those values. For example, I want the School value to show

School: University of Whatever

And the same goes for Field of Study.

Field of Study: Whatever

I know how to do this in vanilla JS but taking the values and appending them to the DOM but it doesn't seem to work that way in React.

class Education extends Component {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit = (e) => {
    e.preventDefault();
    const schoolForm = document.getElementById("school-form").value;
    const studyForm = document.getElementById("study-form").value;
  };

  render() {
    return (
      <>
        <h1 className="title">Education</h1>
        <div id="content">
            <form>
              <label for="school">School</label>
              <input
                id="school-form"
                className="form-row"
                type="text"
                name="school"
              />
              <label for="study">Field of Study</label>
              <input
                id="study-form"
                className="form-row"
                type="text"
                name="study"
              />
              <button onClick={this.onSubmit} className="save">
                Save
              </button>
              <button className="cancel">Cancel</button>
            </form>
          )}
        </div>
      </>
    );
  }
}

export default Education;

CodePudding user response:

You should use state in order to save the values then show it when the user submits.

import React from "react";
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { scool: "", study: "", showOutput: false };
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit = (e) => {
    e.preventDefault();
    this.setState({
      showOutput: true
    });
  };

  setStudy = (value) => {
    this.setState({
      study: value
    });
  };

  setSchool = (value) => {
    this.setState({
      school: value
    });
  };

  render() {
    return (
      <>
        <h1 className="title">Education</h1>
        <div id="content">
          {this.state.showOutput && (
            <>
              <div>{`school: ${this.state.school}`}</div>
              <div>{`study: ${this.state.study}`}</div>
            </>
          )}
          <form>
            <label for="school">School</label>
            <input
              id="school-form"
              className="form-row"
              type="text"
              name="school"
              onChange={(e) => this.setSchool(e.target.value)}
            />
            <label for="study">Field of Study</label>
            <input
              id="study-form"
              className="form-row"
              type="text"
              name="study"
              onChange={(e) => this.setStudy(e.target.value)}
            />
            <button onClick={this.onSubmit} className="save">
              Save
            </button>
            <button className="cancel">Cancel</button>
          </form>
          )
        </div>
      </>
    );
  }
}

export default App;

I have also added 2 functions to set state and a condition render based on showOutput.

CodePudding user response:

You don't append things to the DOM in react like you do in vanilla. You want to conditionally render elements.

Make a new element to display the data, and render it only if you have the data. (Conditional rendering is done with && operator)

{this.state.schoolForm && this.state.studyform && <div>
    <p>School: {this.state.schoolForm}</p>
    <p>Field of Study: {this.state.studyForm}</p>
</div>}

The schoolForm and studyForm should be component state variables. If you only have them as variables in your onSubmit, the data will be lost after the function call ends. Your onSubmit function should only set the state, and then you access your state variables to use the data.

Do not use document.getElementById. You don't want to use the 'document' object with react (Almost never).

You can access the element's value directly using the event object which is automatically passed by onSubmit.

handleSubmit = (event) => {
    event.preventDefault();
    console.log(event.target.school.value)
    console.log(event.target.study.value)
}
  • Related