React - How to Populate two Dropdowns based on selection in another - javascript

I need to change the contents of dropdown Method&Minorhead based on the selection in dropdown MajorHead using React.
If I select cheating in majorhead, then it's supposed to show a&b in minorHead and apple, orange in Method.
If I select abduction in majorhead, then it's supposed to show AB&BC in minorhead and cat, dog in Method...
import React, { Component } from 'react';
class Profile extends Component {
render() {
return (
<form>
<div className="form-group">
<label for="inputState">Major head</label>
<select id="inputState" className="form-control"/>
<option selected>Choose...</option>
<option>Cheating</option>
<option>Abduction</option>
<option>House brake</option>
</div>
<div className="form-group">
<label for="inputState">Minor head</label>
<select id="inputState" className="form-control"/>
<option selected>Choose...</option>
<option>a</option>
<option>b</option>
<option>AB</option>
<option>BC</option>
<option>X</option>
<option>Y</option>
</div>
<div className="form-group">
<label for="inputState">method</label>
<select id="inputState" className="form-control"/>
<option selected>Choose...</option>
<option>apple</option>
<option>orange</option>
<option>cat</option>
<option>dog</option>
</div>
</form>
)
}
}
export default Profile;

For each option in your major head Select, i would create an array of supported values for method and minor.
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
selectedView: 'Cheating'
}
}
render() {
const { selectedView } = this.state
const VIEWS = [
{
name: 'Cheating',
minor: ['a', 'b'],
method: ['apple', 'orange']
}, {
name: 'Abductions',
minor: ['AB', 'BC', 'X'],
method: ['cat', 'dog']
}
]
const getMajorMethod = () => {
const view = VIEWS.filter(({name}) => name === selectedView)[0]
return (
<div>
<select>
{view.minor.map(m => <option>{m}</option>)}
</select>
<select>
{view.method.map(m => <option>{m}</option>)}
</select>
</div>
)
}
return (
<div>
<select onChange={(e) => this.setState({selectedView: e.target.value})}>
{VIEWS.map(({name}) => <option value={name}>{name}</option>)}
</select>
{getMajorMethod()}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
A structure like this will allow you to (within your initial MAJOR select) map over your VIEWS and apply the name prop to the options.
You can then have another map that shows two other selects (minor & method) with the VIEWS relative minor and method arrays being their options

Related

Bind Id through another property React [duplicate]

I'm using react and I want to get the value of the selected option of a dropdown in react but I don't know how. Any suggestions? thanks!
My dropdown is just a select like:
<select id = "dropdown">
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
The code in the render method represents the component at any given time.
If you do something like this, the user won't be able to make selections using the form control:
<select value="Radish">
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
So there are two solutions for working with forms controls:
Controlled Components Use component state to reflect the user's selections. This provides the most control, since any changes you make to state will be reflected in the component's rendering:
example:
var FruitSelector = React.createClass({
getInitialState:function(){
return {selectValue:'Radish'};
},
handleChange:function(e){
this.setState({selectValue:e.target.value});
},
render: function() {
var message='You selected '+this.state.selectValue;
return (
<div>
<select
value={this.state.selectValue}
onChange={this.handleChange}
>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{message}</p>
</div>
);
}
});
React.render(<FruitSelector name="World" />, document.body);
JSFiddle: http://jsfiddle.net/xe5ypghv/
Uncontrolled Components The other option is to not control the value and simply respond to onChange events. In this case you can use the defaultValue prop to set an initial value.
<div>
<select defaultValue={this.state.selectValue}
onChange={this.handleChange}
>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{message}</p>
</div>
http://jsfiddle.net/kb3gN/10396/
The docs for this are great: http://facebook.github.io/react/docs/forms.html
and also show how to work with multiple selections.
UPDATE
A variant of Option 1 (using a controlled component) is to use Redux and React-Redux to create a container component. This involves connect and a mapStateToProps function, which is easier than it sounds but probably overkill if you're just starting out.
Implement your Dropdown as
<select id = "dropdown" ref = {(input)=> this.menu = input}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Now, to obtain the selected option value of the dropdown menu just use:
let res = this.menu.value;
It should be like:
import React, { useState } from "react";
export default function App() {
const getInitialState = () => {
const value = "Orange";
return value;
};
const [value, setValue] = useState(getInitialState);
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<div>
<select value={value} onChange={handleChange}>
<option value="Orange">Orange</option>
<option value="Radish">Radish</option>
<option value="Cherry">Cherry</option>
</select>
<p>{`You selected ${value}`}</p>
</div>
);
}
you can see it here: https://codesandbox.io/s/quizzical-https-t1ovo?file=/src/App.js:0-572
Just use onChange event of the <select> object.
Selected value is in e.target.value then.
By the way, it's a bad practice to use id="...". It's better to use ref=">.."
http://facebook.github.io/react/docs/more-about-refs.html
As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to
use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple
you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown
whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList
1
remember you will always get the result as option value and not the dropdown text which is displayed on the screen
import React, { Component } from "react";
import { Server } from "net";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {
selectValue: ""
};
this.handleDropdownChange = this.handleDropdownChange.bind(this);
}
handleDropdownChange(e) {
this.setState({ selectValue: e.target.value });
}
render() {
return (
<div>
<div>
<div>
<select id="dropdown" onChange={this.handleDropdownChange}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div>Selected value is : {this.state.selectValue}</div>
</div>
</div>
);
}
}
export default InlineStyle;
Using React Functional Components:
const [option,setOption] = useState()
function handleChange(event){
setOption(event.target.value)
}
<select name='option' onChange={handleChange}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
class App extends React.Component {
state = {
selectedOption: null,
};
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
And you can check it out on this site.
It is as simple as that. You just need to use "value" attributes instead of "defaultValue" or you can keep both if a pre-selected feature is there.
....
const [currentValue, setCurrentValue] = useState(2);
<select id = "dropdown" value={currentValue} defaultValue={currentValue}>
<option value="N/A">N/A</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
.....
setTimeut(()=> {
setCurrentValue(4);
}, 4000);
In this case, after 4 secs the dropdown will be auto-selected with option 4.
I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.
In the spirit of the other answers using food examples, I got all sorts of fruit goodness for you.
First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.
Next up, the same example - but juiced up with Typescript.
Then a bonus finale - A language selector dropdown component using Typescript.
Basic React (16.13.1) Functional Component Example. Two examples of FruitSelectDropdown , one without props & one with accepting props fruitDetector
import React, { useState } from 'react'
export const FruitSelectDropdown = () => {
const [currentFruit, setCurrentFruit] = useState('oranges')
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector prop
import React, { useState } from 'react'
export const FruitSelectDropdown = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
FruitSelectDropdown with Typescript
import React, { FC, useState } from 'react'
type FruitProps = {
fruitDetector: string;
}
export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit: string): void => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown elsewhere in your app
import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App: FC = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
Bonus Round: Translation Dropdown with selected current value:
import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
export const LanguageSelectDropdown: FC = () => {
const { i18n } = useTranslation()
const i18nLanguage = i18n.language
const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
const changeLanguage = (language: string): void => {
i18n.changeLanguage(language)
setCurrentI18nLanguage(language)
}
return (
<form>
<select
onChange={(event) => changeLanguage(event.target.value)}
value={currentI18nLanguage}
>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</form>
)
}
An invaluable resource for React/Typescript
You can handle it all within the same function as following
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>
<option value="5">5 dollars</option>
<option value="10">10 dollars</option>
</select>
as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!
If you want to get value from a mapped select input then you can refer to this example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fruit: "banana",
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log("Fruit Selected!!");
this.setState({ fruit: e.target.value });
}
render() {
return (
<div id="App">
<div className="select-container">
<select value={this.state.fruit} onChange={this.handleChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div>
</div>
);
}
}
export default App;
import {React, useState }from "react";
function DropDown() {
const [dropValue, setDropValue ]= useState();
return <>
<div>
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
{dropValue==null || dropValue=='' ?'Select Id':dropValue}
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a class="dropdown-item" onClick={()=> setDropValue('Action')} href="#">Action</a></li>
<li><a class="dropdown-item" onClick={()=> setDropValue('Another action')} href="#">Another action</a></li>
<li><a class="dropdown-item" onClick={()=> setDropValue('Something else here')} href="#">Something else here</a></li>
</ul>
</div>
</div>
</>
}
export default DropDown
<select value ={this.state.value} onChange={this.handleDropdownChange}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
As mentioned by Karen above you can just use the target value from the event triggered. Here is a small snippet of the code
`<select class="form-select py-2"
onChange={(e) => setVotersPerPage(e.target.value)}>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>`

React bulk update documents using select all checkbox

Proper way to do bulk update of documents in react.
I want to bulk update all posts status and type fields in one single query how to achieve it.
Status and Type are dropdown select inputs.
All Posts Component:-
const AllPosts = () => {
const [updateObj ,setUpdateObj] = useState({})
handleUpdate(){
}
return (
<>
<div>
{AllPosts.map((post, index) => (
<Post
key={post._id}
postId={post._id}
postStatus={post.status}
postType={post.type}
postSubject={post.subject}
checked={post?.isChecked || false}
onChange={handleAllChecked}
checkBoxName={post._id}
/>
))}
</div>
</>
);
};
export default AllPosts;
I think I would need an update object which would have post id as key and status and type as its value.
Post component
const Post = ({
postId,
postStatus,
postType,
postSubject,
checked,
onChange,
checkBoxName,
}) => {
return (
<div className="post">
<div className="post-checkbox">
<input
type="checkbox"
id="post-checkbox"
name={checkBoxName}
checked={checked}
onChange={onChange}
/>
</div>
<div>
<div>{postSubject}</div>
<div className="options">
<select onChange={onChange}>
<option>Status A</option>
<option>Status B</option>
<option>Status C</option>
</select>
<select onChange={onChange}>
<option>Type A</option>
<option>Type B</option>
<option>Type C</option>
</select>
</div>
</div>
</div>
);
};
export default Post;

How to get the value of a dropdown menu in ReactJS

I'm trying to get the value of a dropdown menu that looks like this:
<ul className="tabs" data-component={true}>
<li>
<section className="sort-list" data-component={true}>
<select value={0} className="sort" data-element={true}>
<option key="0" value="0">Any Topic</option>
<option key="1" value="1">Art</option>
<option key="2" value="2">Auto</option>
//...and so on
I've seen similar questions, but trying to alert(sort).value won't work (along with some other variants) so I think I need to string together my selectors?
I can use either the value or the text, as the goal is to keep the filter applied even when a user goes back to the previous page.
How do I get the key, value, or text of the options?
You need to add onchage event to your select.
change = (event) => {
this.setState({
topic: event.target.value
})
}
<select onChange={this.change} value={0} className="sort" data-element={true}
<option key="0" value="0">Any Topic</option>
<option key="1" value="1">Art</option>
<option key="2" value="3">Auto</option>
</select>
DEMO
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
constructor() {
super();
this.state = {
topic: ''
};
}
change = (event) => {
this.setState({
topic: event.target.value
})
}
render() {
return (
<div>
<p>
Selected topic: {this.state.topic}
</p>
<select onChange={this.change} className="sort" data-element={true}>
<option key="0" value="0">Any Topic</option>
<option key="1" value="1">Art</option>
<option key="2" value="2">Auto</option>
</select>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>
The Reactjs way would be to have a select box component which has an onChange handler. Something like this:
class MySelect extends React.Component {
onChange = (val) => {
// save the val somewhere..
this.setState({currentVal: val})
}
render() {
return <select onChange={this.onChange}> { getOptions() } </select>
}
}
Add onChange property to element.
Here is a simple code snippet for a working example.
import React, { useState } from 'react';
import { oneOfType, string, number } from 'prop-types';
function MyDropdown({ selected: preSelected }) {
const [selected, setSelected] = useState(preSelected);
const onChange = evt => {
setSelected(evt.target.value);
}
return (
<div>
<select onChange={onChange} value={selected}>
<option value={1}>Opption 1</option>
<option value={2}>Opption 2</option>
<option value={3}>Opption 3</option>
</select>
{selected && <div>Selcted: {selected}</div>}
</div>
)
}
MyDropdown.propTypes = {
selected: oneOfType([string, number])
};
MyDropdown.defaultProps =
selected: 1
};
You can also check it live on CodeSandbox: https://codesandbox.io/s/react-codesandbox-2voc6

How to get data from javascript array object / JSON and use it in React JS

I am developing a React Js website. Where I have a form with 4 select fields Make, Model, Min price and Max price. I have a javascript file which contains make and models of cars.
File contains multiple Car Makes. File data is available below which represent Car Make and its available models in array.
export const veh_data = [{"alfa-romeo": ["145", "90", "Alfa 6", "Alfasud"]},
{"aston-martin": ["15", "2-Litre", "AM Vantage", "Atom", "Cygnet", "DB2"]},
{"audi": ["100", "200", "A1", "A2", "A3", "A4", "A5", "A6", "A7" ]}
];
I want to get that data (Make name (e.g audi) and its Models) from this file and display that data as options of Select fields in the form.
Here is my React JS component code:
import React, { Component } from 'react';
import { Form, FormGroup, Input } from 'reactstrap';
import { veh_data } from '../shared/vehicle_make_and_models'
class ImgAndForm extends Component {
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
this.state = {
veh_data: veh_data,
};
}
handleSearch(event) {
alert("Search button clicked");
event.preventDefault();
}
render() {
const veh_make = this.state.veh_data.map((veh) => {
return (
<div>
<option></option>
</div>
);
});
return (
<div>
<header className="headerbg d-flex">
<div className="container my-auto">
<div className="row">
<div className="offset-1 col-10 offset-lg-0 col-lg-4">
<div id="search-form-div" className="container">
<div className="row">
<div className="col-12 my-4">
<h3>Search</h3>
<Form onSubmit={this.handleSearch}>
<FormGroup>
<Input type="select" name="select1" id="select1">
<option value="">Make</option>
{veh_make}
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select2" id="select2">
<option value="">Model</option>
{veh_make}
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select3" id="select3">
<option value="">Min Price</option>
<option value="500">500</option>
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select4" id="select4">
<option value="">Max Price</option>
<option value="2000">2000</option>
</Input>
</FormGroup>
<FormGroup>
<Input type="submit" name="search" id="search" className="btn btn-primary" value="Search" />
</FormGroup>
</Form>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
</div>
);
}
}
export default ImgAndForm;
First you need to parse the vehicle values into separate arrays of JSX options elements. I prefer to do this with a reduce function...
const vehicles = this.state.veh_data.reduce((acc, veh) => {
let make = Object.keys(veh)[0],
vehModels = veh[make];
return {
makes: [
...acc.makes,
<option value={make}>{make}</option>
],
models:[
...acc.models,
...vehModels.map(model => {
return <option value={model}>{model}</option>
})
]
};
},{makes:[], models:[]});
Since each element in your veh_data array is an object you need to access its first (and only) property with Object.keys() to get all keys of the object, then just grab the first (and only) key.
Model can be access by getting the value of that key in each veh object you're iterating over
...
<FormGroup>
<Input type="select" name="select1" id="select1">
<option selected disabled>Make</option>
{vehicles.makes}
</Input>
</FormGroup>
...
<FormGroup>
<Input type="select" name="select2" id="select2">
<option selected disabled>Model</option>
{vehicles.models}
</Input>
</FormGroup>
...
Given the context I also don't see a need to store the veh_data to the component state, which is a waste of resources unless that data will be updating the UI dynamically so this would be the complete solution....
https://jsfiddle.net/mfpv1L6s/
(NOTE: I understand this won't give you the full solution you 'should' be looking for as it will show the model options for every vehicle rather than the only the models related to the currently selected 'make', but this should be a good starting point for you.)
EXTRA CREDIT: I'd also parse out the option presentation values to something a little more attractive like this...
keyToOption(key){
return key.split('-')
.map(word=> word.slice(0,1).toUpperCase + word.slice(1))
.join(' ');
}
Then add it to the reduce function like this...
makes: [
...acc.makes,
<option value={make}>{this.keyToOption(make)}</option>
],
I've included the above in the JSFiddle
(Complete working example....)
import React, { Component } from "react";
import { Form, FormGroup, Input } from "reactstrap";
// import { veh_data } from '../shared/vehicle_make_and_models'
const veh_data = [
{ "alfa-romeo": ["145", "90", "Alfa 6", "Alfasud"] },
{ "aston-martin": ["15", "2-Litre", "AM Vantage", "Atom", "Cygnet", "DB2"] },
{ audi: ["100", "200", "A1", "A2", "A3", "A4", "A5", "A6", "A7"] }
];
const vehicles = parseVehicleList(veh_data)
class ImgAndForm extends Component {
state = { modelSelected: null };
handleSearch(event) {
alert("Search button clicked");
event.preventDefault();
}
handleModelChange(event) {
console.log(event.target.value);
this.setState({ modelSelected: event.target.value });
}
render() {
const selectedModels =
this.state.modelSelected && this.state.modelSelected.length ? (
vehicles.models[this.state.modelSelected]
) : (
<option value="">(Please Select Make)</option>
);
return (
<div>
<header className="headerbg d-flex">
<div className="container my-auto">
<div className="row">
<div className="offset-1 col-10 offset-lg-0 col-lg-4">
<div id="search-form-div" className="container">
<div className="row">
<div className="col-12 my-4">
<h3>Search</h3>
<Form onSubmit={this.handleSearch}>
<FormGroup>
<Input
onChange={e => this.handleModelChange(e)}
type="select"
name="select1"
id="select1"
>
<option value="">Make</option>
{vehicles.makes}
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select2" id="select2">
{selectedModels}
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select3" id="select3">
<option value="">Min Price</option>
<option value="500">500</option>
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select4" id="select4">
<option value="">Max Price</option>
<option value="2000">2000</option>
</Input>
</FormGroup>
<FormGroup>
<Input
type="submit"
name="search"
id="search"
className="btn btn-primary"
value="Search"
/>
</FormGroup>
</Form>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
</div>
);
}
}
export default ImgAndForm;
function parseVehicleList(data) {
return data.reduce(
(acc, veh, i) => {
let make = Object.keys(veh)[0],
vehModels = veh[make];
return {
makes: [
...acc.makes,
<option key={make + i} value={make}>
{keyToOption(make)}
</option>
],
models: {
...acc.models,
[make]: vehModels.map((model, i) => {
return (
<option key={make + model + i} value={model}>
{keyToOption(model)}
</option>
);
})
}
};
},
{ makes: [], models: {} }
);
}
function keyToOption(key) {
return key
.split("-")
.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
.join(" ");
}

Sorting and filtering in react

In the following code block, I want to perform sorting and filtering according to the panels I have defined on top. User can select sorting criteria and order to sort the data. User can select the criteria and related values to get the filtered results. Note: first I want to pull dynamic drop down according to the selected criteria while filtering.
class StudentRow extends React.Component {
render() {
const student = this.props.student;
return (
<tr>
<td>{student.ID}</td>
<td>{student.Name}</td>
<td>{student.Age}</td>
<td>{student.Major}</td>
<td>{student.College}</td>
</tr>
);
}
}
class DropDown extends React.Component {
constructor(props) {
super(props);
this.state = {criteria: 'id', order: 'ascending'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleSubmit(event) {
alert('Your cretiria is: ' + this.state.criteria + ' Order is: ' + this.state.order);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Cretiria to sort:
<select value={this.state.criteria} name="criteria" onChange={this.handleChange}>
<option value="id">ID </option>
<option value="name">Name </option>
<option value="age">Age </option>
<option value="major">Major </option>
<option value="college">College</option>
</select>
</label>
<label>
Order of sorting:
<select value={this.state.order} name="order" onChange={this.handleChange}>
<option value="ascending">Ascending</option>
<option value="descending">Descending</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
class Filter extends React.Component {
constructor(props) {
super(props);
this.state = {criteria: 'id', value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleSubmit(event) {
alert('Your cretiria is: ' + this.state.criteria + ' Value is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Cretiria to filter:
<select value={this.state.criteria} name="criteria" onChange={this.handleChange}>
<option value="id">ID </option>
<option value="name">Name </option>
<option value="age">Age </option>
<option value="major">Major </option>
<option value="college">College</option>
</select>
</label>
<label>
Value to filer:
<select value={this.state.value} name="value" onChange={this.handleChange}>
// Need dynamic values here
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
const filtereData = data.filter(item => item.value === valuetofilter);
<label>
Value to filer:
<select value={this.state.value} name="value" onChange={this.handleChange}>
{filteredData.map(item => <option value={item.value}> {item.value} </option>}
</select>
</label>
replace item.value with the value from the data you want to use to compare. Then valuetofilter is the value from the state that the user queried. If it matches a new option element will be returned into the select.

Categories