Display a form based on the option selection in React - reactjs

I have a form component and i want to show and hide 3 different forms based on the first selection in the option. What's the best way to do this dynamically with state?
class Form extends Component {
state = {
selectedValue: ''
};
render() {
const formStyle = {
display: 'none'
}
return (
<div className={styles.ContactUs}>
<form >
<select>
<option value="" selected="selected"></option>
<option value="form_name1">Form 1</option>
<option value="form_name2">Form 2</option>
<option value="form_name3">Form 3</option>
</select>
</form>
{
this.state.selectedValue === id.value ?
<form name="form_name1" id="form_name1" style={formStyle}>
form 1
</form> : null
}
<form name="form_name2" id="form_name2" style={formStyle} >
form 2
</form>
<form name="form_name3" id="form_name3" style={formStyle} >
form 3
</form>
</div>
);
}
}
export default Form;

you can use nested if else if and state to check what should be displayed. Example code is give below
class App extends Component {
constructor(){
super();
this.state = {
selected:2
}
}
render() {
return (
<div>
{
this.state.selected == 1 ? (
<div> I am form 1 </div>
) : this.state.selected == 2 ? (
<div> I am form 2 </div>
) : this.state.selected == 3 ? (
<div> I am form 3 </div>
) : null
}
</div>
);
}
}
export default App;

Try like this
class Form extends Component {
constructor(){
super();
this.state = {
selectedValue:''
}
this.handleChange = this.handleChange.bind(this);
}
renderSelectedForm(param) {
switch(param) {
case 'form_name1':
return <form name="form_name1" id="form_name1" style={formStyle}>
form 1
</form>;
case 'form_name2':
return <form name="form_name1" id="form_name2" style={formStyle}>
form 2
</form>;
case 'form_name3':
return <form name="form_name1" id="form_name3" style={formStyle}>
form 3
</form>;
default:
return null;
}
}
handleChange(event) { this.setState({selectedValue: event.target.value}); }
render() {
return (
<div>
<div className={styles.ContactUs}>
<form >
<select value={this.state.selectedValue} onChange={this.handleChange}>
<option value="" selected="selected"></option>
<option value="form_name1">Form 1</option>
<option value="form_name2">Form 2</option>
<option value="form_name3">Form 3</option>
</select>
</form>
{this.renderSelectedForm(this.state.selectedValue)}
</div>
);
}

Related

Two dropdowns in a React Form

I want to get the users input of a form with two drop-downs, and store it inside a global variable using react. I looked at reacts docs on how to create forms, and manipulate their code a little bit to have two drop-downs, but can't get it to save the variable as a global variable and print that global variable onto the screen. Unfortunately, there was an error when I clicked the second submit button (The first button did nothing). Here was the error: TypeError: this is undefined handleSubmit src/App.js:55 52 | } 53 | handleSubmit(event) { 54 | event.preventDefault(); > 55 | two = this.state.value | ^ 56 | } 57 | 58 | render() { – . Here was my code inside App.js:
import React from "react";
import "./App.css";
var one = "";
var two = "";
class FlavorFormOne extends React.Component {
constructor(props) {
super(props);
this.state = { value: "coconut" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
one = this.state.value
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
class FlavorFormTwo extends React.Component {
constructor(props) {
super(props);
this.state = { value: "GrabeFruit" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
two = this.state.value
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="submit"/>
</form>
</div>
);
}
}
function App() {
return (
<>
<FlavorFormOne />
<FlavorFormTwo />
{one}
{two}
</>
);
}
export default App;
you didn't pass the event
try onSubmit={(e)=>this.handleSubmit(e)}
also onChange={(e)=>this.handleChange(e)}
There were a couple things that needed to be fixed in your code. The first was this.handleSubmit = this.handleSubmit.bind(this); needed to be added in FlavorFormTwo's constructor, as I mentioned in the comments. The second was your handling of global variables. React won't re-render a component when a global variable changes, but it will re-render when the state is changed with setState. This is the reason why react state doesn't update when using this.state =. Instead, I added onSubmit as a prop to both, and inside both handleSubmit functions I added this.props.onSubmit(this.state.value). I changed the App component to a class, and added functions for handleOneSubmit and handleTwoSubmit that set the state of app. Try it online: https://codesandbox.io/s/vibrant-smoke-tsgri?file=/src/App.js
import React from "react";
import "./App.css";
class FlavorFormOne extends React.Component {
constructor(props) {
super(props);
this.state = { value: "coconut" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
this.props.onSubmit(this.state.value);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
class FlavorFormTwo extends React.Component {
constructor(props) {
super(props);
this.state = { value: "GrabeFruit" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
this.props.onSubmit(this.state.value);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="submit" />
</form>
</div>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { one: "", two: "" };
this.handleOneSubmit = this.handleOneSubmit.bind(this);
this.handleTwoSubmit = this.handleTwoSubmit.bind(this);
}
handleOneSubmit(value) {
this.setState({ one: value });
}
handleTwoSubmit(value) {
this.setState({ two: value });
}
render() {
return (
<>
<FlavorFormOne onSubmit={this.handleOneSubmit} />
<FlavorFormTwo onSubmit={this.handleTwoSubmit} />
{this.state.one}
{this.state.two}
</>
);
}
}
export default App;

As from an array of fields, you can save the entered values?

I am trying to get the value from inpit and store it. I create an array in which I put the selected number of "input", then iterate over the array and output the data. The task is to get the entered value into all "inputs" and save them. Tried using "e.target", the solution didn't help. Tell me how you can implement it?
class Rules extends Component {
constructor(props) {
super(props);
this.state = {
newNameColumns: [],
}
};
handleChange(value) {
let newInputColumns = []
for (let i = 0; i < value; i++) {
newInputColumns.push({
key: this.setState({count: this.state.count + 1}),
input: <Input />
});
}
this.setState({newNameColumns: [...this.state.newNameColumns, ...newInputColumns]});
}
render() {
const {newNameColumns} = this.state;
const dataTableRules =
<div className="modal-create-table">
<Input placeholder="enter title rule"/>
<Select defaultValue="0" style={{width: 220}} onChange={this.handleChange.bind(this)}>
<Option value="1">1</Option>
<Option value="2">2</Option>
<Option value="3">3</Option>
<Option value="4">4</Option>
</Select>
</div>;
return (
<div className="rules">
<TableRules/>
<Modal
newNameColumns={newNameColumns}
/>
</div>
)
}
}
{props.newNameColumns.map(item => (
<div className="new-input-columns-name" key={item.key}>{item.input}</div>
))}
Try using event.target.value in change handler.
handleChange(event) {
...
this.setState({tableAmountColumns: event.target.value});
...
}

componentDidUpdate function doesn't get called

I've created a React component to render another component inside.when I change the select element in the parent component the componentDidUpdate function doesn't get called in the child component
component1:
let ExtraParam = [];
const handleChange = (e) => {
ExtraParam[e.target.name] = e.target.value;
}
const Flights = () => {
return (
<div>
<div className="row">
<div className='col-6 col-md-3 mt-5'>
<select onChange={handleChange} name="age" className="browser-default custom-select">
<option>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</div>
<Datatable Api='/api/Flights' Columns={columns} extraParam {ExtraParam} />
</div>
)
}
component2:
componentDidUpdate(prevProps) {
if (this.props.extraParam !== prevProps.extraParam)
{
console.log('changed');
}
}

Prooblem on select in react

I want to create a select component of Blood group option. I write code and it does render on dom but it is not showing up in the browser.
This is FindDonor Component
import React, { Component } from "react";
class FindDonor extends Component {
state = {
value: "Find Donor By Blood Group"
};
handleChange = e => {
this.setState({ value: e.target.value });
};
render() {
return (
<div className="findDonor">
<h1>Hello</h1>
<div className="input-field">
<select value={this.state.value} onChange={this.handleChange}>
<option value="a+">A+</option>
<option value="o+">O+</option>
<option value="b+">B+</option>
<option value="ab+">AB+</option>
<option value="a-">A-</option>
<option value="o-">O-</option>
<option value="b-">B-</option>
<option value="ab-">AB-</option>
</select>
</div>
</div>
);
}
}
export default FindDonor;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Home Component code
Home.js
App Component code
App.js
You are probably missing a this.handleChange = this.handleChange.bind(this); in your constructor.
Check this example from the React docs (https://reactjs.org/docs/forms.html#the-select-tag):
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
I think you need to pass event on your onChange onChange={(e) => {this.handleChange(e)}. Also, in case of arrow functions, there is no need to bind functions.
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
}
handleChange = (event) => {
this.setState({value: event.target.value});
}
handleSubmit = (event) => {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={(e) => {this.handleChange(e)}}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}

onchange of one select other select option should change and i should get the data in alert of submit

Hi all I am unable to set the value of value1 if I am changing the value from parent select. I am able to render different select on changing the options of parent select, but I am not able to set the value.
import React, { Component } from 'react';
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'HR',value1 : '1'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange1 = this.handleChange1.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
alert(this.state.value , this.state.value1);
}
getsecondselect = () => {
if(this.state.value === "HR"){
//gethrcontent = () => {
return (
<label>
Pick your HR:
<select value1={this.state.value1} onChange={this.handleChange1}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</label>
)//};
}
else{
//getslectedenrollment = () => {
return (
<label>
Pick your Enrollment:
<select value1={this.state.value1} onChange={this.handleChange1}>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</label>
)//};
}
}
handleChange1(event) {
this.setState({value1: event.target.value1});
alert(this.state.value1);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="HR">HR</option>
<option value="enrollment">enrollment</option>
</select>
</label>
{getsecondselect()}
<input type="submit" value="Submit" />
</form>
);
}
}
export default FlavorForm;
I made some changes to the code, but as stackoverfloweth mentioned, you had event.target.value1 instead of event.target.value.
Also, you need this.getsecondselect() in the render function of the code you posted.
Working CodeSandbox here.
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
state = {
value: "HR",
number: "1"
};
handleChangeValue = event => {
this.setState({ value: event.target.value });
};
handleSubmit = event => {
event.preventDefault();
alert(`${this.state.value} --> ${this.state.number}`);
};
getSecondSelect = () => {
if (this.state.value === "HR") {
return (
<label>
Pick your HR:
<select value1={this.state.number} onChange={this.handleChangeNumber}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</label>
); //};
} else {
//getslectedenrollment = () => {
return (
<label>
Pick your Enrollment:
<select value1={this.state.value1} onChange={this.handleChangeNumber}>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</label>
); //};
}
};
handleChangeNumber = event => {
this.setState({ number: event.target.value });
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChangeValue}>
<option value="HR">HR</option>
<option value="enrollment">enrollment</option>
</select>
</label>
{this.getSecondSelect()}
<input type="submit" value="Submit" />
</form>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
It looks like both of your selects are setup to have value={this.state.value1} and onchange they both call this.handleChange1. Not sure if that's an issue.
I also noticed that within handleChange1 you are updating the state with a prop event.target.value1 but the options do not have value1 defined.. perhaps you meant to use event.target.value?
Hope this helps

Resources