How can I get the selected element when I submit the form. I'm using reactjs autosuggest.
My Parent Component
<Form
onSubmit={this.submitFormadd}
layout="horizontal"
ref="myformadd"
>
<MyAutosuggest
data={this.props.users}
id="river"
name="river"
placeholder="Enter River Name"
onChange={this.onChange}
required="true"
/>
<MyAutosuggest
data={this.props.drivers}
id="driver"
name="driver"
placeholder="Enter Driver Name"
onChange={this.onChange}
/>
<fieldset>
<Row layout="horizontal">
<input className="btn btn-primary" formNoValidate={true} type="submit" defaultValue="Submit" />
</Row>
</fieldset>
</Form>
You have set onChange wrongly for the autosuggests. Change:
onChange={this.onChange}
to
onChange={this.onChange.bind(this)}
Then store the selected elements in the onChange method. When the submit is triggered, you will have the elements already stored.
<Autosuggest
id="river"
name="river"
placeholder="Enter River Name"
onChange={this.onChange}
required="true"
data={this.props.users}
getSuggestionValue={this.getSuggestionValue.bind(this)}/>
I think the above code would help, in getSuggestionValue, you will get value, which you can use,
for example:
getSuggestionValue(value){
this.setState({ val:value}); //or anything else
}
while submitting (example):
submitFunction(){
console.log(this.state.val); //receive value here
}
changes in code from codepen
const languages = [
{
name: 'C',
year: 1972
},
{
name: 'C#',
year: 2000
},
{
name: 'C++',
year: 1983
},
{
name: 'Clojure',
year: 2007
},
{
name: 'Elm',
year: 2012
},
{
name: 'Go',
year: 2009
},
{
name: 'Haskell',
year: 1990
},
{
name: 'Java',
year: 1995
},
{
name: 'Javascript',
year: 1995
},
{
name: 'Perl',
year: 1987
},
{
name: 'PHP',
year: 1995
},
{
name: 'Python',
year: 1991
},
{
name: 'Ruby',
year: 1995
},
{
name: 'Scala',
year: 2003
}
];
// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters
function escapeRegexCharacters(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getSuggestions(value) {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return languages.filter(language => regex.test(language.name));
}
function getSuggestionValue(suggestion) {
return this.props.getValue(suggestion.name,this.props.id);
}
function renderSuggestion(suggestion) {
return (
<span>{suggestion.name}</span>
);
}
class MyAutosuggest extends React.Component {
constructor() {
super();
this.state = {
value: '',
suggestions: []
};
}
onChange = (_, { newValue }) => {
const { id, onChange } = this.props;
this.setState({
value: newValue
});
onChange(id, newValue);
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
render() {
const { id, placeholder } = this.props;
const { value, suggestions } = this.state;
const inputProps = {
placeholder,
value,
onChange: this.onChange
};
return (
<Autosuggest
id={id}
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
);
}
}
class App extends React.Component {
onChange(id, newValue) {
console.log(`${id} changed to ${newValue}`);
}
getValueForInput(val,id){
console.log(val,id);
}
render() {
return (
<div>
<MyAutosuggest
id="type-c"
placeholder="Type 'c'"
onChange={this.onChange}
getValue={this.getValueForInput.bind(this)}
/>
<MyAutosuggest
id="type-p"
placeholder="Type 'p'"
onChange={this.onChange}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Here is how I did it.
onChange = (event, { newValue, method }) => {
let bookObj;
if (method == "click") {
this.props.bookiesList.filter(book=> {
if (book.name.trim() === newValue.trim()) {
bookObj= book
}
});
}
};
Related
I am using Ant Design to create a cascading dropdown. I am looking to return the selected value as a tag to display something like "You selected {name}". How can I bind the selected value to the h1 tag? Here is the code so far:
const options = [
{
value: 'Person',
label: 'person',
children: [
{
value: 'amy',
label: 'Amy',
},
{
value: 'john',
label: 'John'
}
],
}
];
function onChange(value, selectedOptions) {
console.log(value, selectedOptions);
}
function filter(inputValue, path) {
return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
}
class CascadingDropdown extends Component{
render(){
return(
<div>
<p>Please select a person:</p>
<div>
<Cascader
options={options}
onChange={onChange}
placeholder="Please select"
showSearch={{ filter }}
onSearch={value => console.log(value)}
/>
</div>
<h1>You selected {name}</h1> // here is where I want to print the name
</div>
);
}
}
export default CascadingDropdown;
Use can use state to display the selected value as shown in the following code
const options = [
{
value: 'Person',
label: 'person',
children: [
{
value: 'amy',
label: 'Amy',
},
{
value: 'john',
label: 'John',
},
],
},
];
class CascadingDropdown extends Component {
onChange(value, selectedOptions) {
console.log(value, selectedOptions);
if (value != undefined) {
this.setState({ name: value[1].toString() });
}
}
filter(inputValue, path) {
return path.some(
(option) =>
option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
);
}
constructor(props) {
super(props);
this.state = {
name: '',
};
}
render() {
return (
<div>
<p>Please select a person:</p>
<div>
<Cascader
options={options}
onChange={this.onChange.bind(this)}
placeholder="Please select"
showSearch={this.filter}
onSearch={(value) => console.log(value)}
/>
</div>
<h1>You selected {this.state.name}</h1>
</div>
);
}
}
Screenshot:
Goal:
Display react bootstrap's modal when you press the button 'Open Modal'
Problem:
I do not know how to make it to show bootstrap's modal when I press the button 'Open Modal'
What part am I missing?
Stackblitz:
https://stackblitz.com/edit/react-bootstrap-examples-suktpo?
Info:
*I'm newbie in Reactjs
Thank you!
index.html
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<div id="root"></div>
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import DisplayModalContent from './DisplayModalContent';
import { Modal, Button } from 'react-bootstrap';
class App extends Component {
constructor() {
super();
this.state = {
openItem: null,
items: [
{
firstName: 'Josef',
lastName: 'Anderson',
key: 'josef.anderson',
startYear: 2021,
startMonth: 2
},
{
firstName: 'Jim',
lastName: 'West',
key: 'jim.west',
startYear: 2020,
startMonth: 3
},
{
firstName: 'Joe',
lastName: 'West',
key: 'joe.west',
startYear: 1998,
startMonth: 10
}
],
firstName: '',
lastName: ''
};
}
handleOpenModal = openItem => {
this.setState({ openItem });
};
handleCloseModal = () => {
this.setState({ openItem: null });
};
handleOpenItemValue = e => {
let { name, value } = e.target;
this.setState({
openItem: { ...this.state.openItem, [name]: value }
});
};
handleSubmit = () => {
console.log(document.getElementsByName('startMonth')[0].value);
alert(
JSON.stringify({
test: document.getElementsByName('startMonth')[0].value
})
);
};
render() {
const { items, openItem } = this.state;
return (
<div>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th />
</tr>
</thead>
<tbody>
{items.map(item => {
const { firstName, lastName, key } = item;
return (
<tr key={key}>
<td>{firstName}</td>
<td>{lastName}</td>
<td>
<button onClick={() => this.handleOpenModal(item)}>
Open Modal
</button>
</td>
</tr>
);
})}
</tbody>
</table>
<DisplayModalContent item={openItem} />
</div>
);
}
}
render(<App />, document.getElementById('root'));
DisplayModalContent.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import { Modal, Button } from 'react-bootstrap';
const options = [
{ value: 1, label: 'Jan' },
{ value: 2, label: 'Feb' },
{ value: 3, label: 'Mars' },
{ value: 4, label: 'April' },
{ value: 5, label: 'May' },
{ value: 6, label: 'June' },
{ value: 7, label: 'July' },
{ value: 8, label: 'August' },
{ value: 9, label: 'Sept' },
{ value: 10, label: 'Oct' },
{ value: 11, label: 'Nov' },
{ value: 12, label: 'Dec' }
];
class DisplayModalContent extends Component {
constructor() {
super();
this.state = {
openItem: null,
firstName: '',
lastName: ''
};
}
componentDidUpdate(s) {
if (JSON.stringify(this.props) !== JSON.stringify(s)) {
this.setState({ openItem: this.props.item });
}
}
handleOpenModal = openItem => {
this.setState({ openItem });
};
handleCloseModal = () => {
this.setState({ openItem: null });
};
handleOpenItemValue = e => {
let { name, value } = e.target;
this.setState({
openItem: { ...this.state.openItem, [name]: value }
});
};
handleSubmit = () => {
console.log(document.getElementsByName('startMonth')[0].value);
alert(
JSON.stringify({
test: document.getElementsByName('startMonth')[0].value
})
);
};
hideShowModal = () => {
this.setState({ isModalOpen: !this.state.isModalOpen });
};
render() {
const { items, openItem } = this.state;
return (
<div>
{openItem !== null && (
<div isOpen={true}>
<Button variant="primary" onClick={() => this.hideShowModal()}>
Click to hide/show
</Button>
<Modal
show={this.state.isModalOpen}
onHide={() => this.hideShowModal()}
>
<Modal.Header closeButton>
<Modal.Title>This is modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
First Name:
<br />
<input
type="text"
id="firstName"
name="firstName"
value={openItem.firstName}
onChange={e => this.handleOpenItemValue(e)}
/>
<input
type="text"
id="lastName"
name="lastName"
value={openItem.lastName}
onChange={e => this.handleOpenItemValue(e)}
/>
</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary">CLOSE</Button>
<Button variant="primary">SAVE</Button>
</Modal.Footer>
</Modal>
</div>
)}
</div>
);
}
}
export default DisplayModalContent;
you don't have to use the state in the two components, just define the state in the parent component and pass it as a prop to the child component.
index.js
import React, { Component } from "react";
import DisplayModalContent from "./DisplayModalContent";
import { Modal, Button } from "react-bootstrap";
const items = [
{
firstName: "Josef",
lastName: "Anderson",
key: "josef.anderson",
startYear: 2021,
startMonth: 2
},
{
firstName: "Jim",
lastName: "West",
key: "jim.west",
startYear: 2020,
startMonth: 3
},
{
firstName: "Joe",
lastName: "West",
key: "joe.west",
startYear: 1998,
startMonth: 10
}
];
class App extends Component {
constructor() {
super();
this.state = {
open: false,
openItem: null,
items: [],
firstName: "",
lastName: ""
};
}
componentDidMount() {
this.setState({ items });
}
handleOpenModal = (openItem) => {
this.setState({ openItem, open: true });
};
handleCloseModal = () => {
this.setState({ open: false });
};
handleOpenItemValue = (e) => {
let { name, value } = e.target;
this.setState({
openItem: { ...this.state.openItem, [name]: value }
});
};
handleSubmit = (key) => {
const { openItem, items } = this.state;
const updatedItems = items.filter((i) => i.key !== key);
this.setState({
open: false,
items: [...updatedItems, openItem]
});
// console.log(document.getElementsByName("startMonth")[0].value);
// alert(
// JSON.stringify({
// test: document.getElementsByName("startMonth")[0].value
// })
// );
};
render() {
const { items, openItem, open } = this.state;
return (
<div>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th />
</tr>
</thead>
<tbody>
{items &&
items.map((item) => {
const { firstName, lastName, key } = item;
return (
<tr key={key}>
<td>{firstName}</td>
<td>{lastName}</td>
<td>
<button onClick={() => this.handleOpenModal(item)}>
Open Modal
</button>
</td>
</tr>
);
})}
</tbody>
</table>
<DisplayModalContent
item={openItem}
isOpen={open}
onClose={this.handleCloseModal}
onSubmit={this.handleSubmit}
handleOpenItemValue={(e) => this.handleOpenItemValue(e)}
/>
<br />
<div> {JSON.stringify(items)} </div>
</div>
);
}
}
export default App;
DisplayModalContent.js
import React, { Component } from "react";
import { Modal, Button } from "react-bootstrap";
const options = [
{ value: 1, label: "Jan" },
{ value: 2, label: "Feb" },
{ value: 3, label: "Mars" },
{ value: 4, label: "April" },
{ value: 5, label: "May" },
{ value: 6, label: "June" },
{ value: 7, label: "July" },
{ value: 8, label: "August" },
{ value: 9, label: "Sept" },
{ value: 10, label: "Oct" },
{ value: 11, label: "Nov" },
{ value: 12, label: "Dec" }
];
class DisplayModalContent extends Component {
render() {
const { item, isOpen, onClose, handleOpenItemValue, onSubmit } = this.props;
return (
<div>
<div>
<Modal show={isOpen} onHide={onClose}>
<Modal.Header closeButton>
<Modal.Title>This is modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
First Name:
<br />
<input
type="text"
id="firstName"
name="firstName"
value={item && item.firstName}
onChange={(e) => handleOpenItemValue(e)}
/>
<input
type="text"
id="lastName"
name="lastName"
value={item && item.lastName}
onChange={(e) => handleOpenItemValue(e)}
/>
</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={onClose}>
CLOSE
</Button>
<Button variant="primary" onClick={() => onSubmit(item.key)}>
SAVE
</Button>
</Modal.Footer>
</Modal>
</div>
</div>
);
}
}
export default DisplayModalContent;
Live working Demo
I was reviewing your code and I see you're using this.state.isModalOpen to show the modal, but in the DisplayModalContent component that state is never updated when you're receiving the props from your index. So, the easy fix for that is update isModalOpen when you are receiving the props. However, from my experience I would recommend do not use a new state to handle the modal open state in the DisplayModalContent component, you can use it directly from the props:
<DisplayModalContent
item={openItem}
isOpen={!!openItem}
onClose={this.handleCloseModal}
/>
and in your DisplayModalContent component, you can replace any local state and in order to use the component props:
...
<Modal
show={this.props.isOpen}
onHide={this.props.onClose}
>
...
By doing this your code will be more simple and readable.
I have a list of li elements that is being passed down to one of my components. These are being rendered in the component. I have a search bar in the same component. I want to be able to only render the items that match what is written down in the search bar. This is what my component looks like.
import React, {Component} from 'react'
import {NavLink} from 'react-router-dom'
import LikeBtn from './LikeBtn'
class SearchForm extends Component {
constructor(props) {
super(props)
this.state = {
search: '',
newList: []
}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
}
render() {
let list = this.props.listProp.map(item => <li className="listItem" key={item.id}><NavLink style={{ color: 'white' }} to={`activities/${item.id}`}>{item.name}</NavLink><LikeBtn /></li>)
let newList = list.filter(item => item.innerText === this.state.search)
console.log(newList)
return (
<>
<input type="text" name='search' onChange={this.handleChange}/>
<ul>
{list}
</ul>
</>
)
}
}
export default SearchForm
I don't know how to get that filtered out so that I can render the items. I tried doing innerText but since I have a LikeBtn component in the li element my filter doesn't work. How else would I be able to implement this? Are there more efficient ways of doing this?
You need to filter your data and not grab something you've already rendered on screen.
render() {
let filteredList = this.state.search
? this.props.listProp.filter((item) =>
item.name.includes(this.state.search),
)
: this.props.listProp;
return (
<>
<input type="text" name="search" onChange={this.handleChange} />
<ul>
{filteredList.map((item) => (
<li className="listItem" key={item.id}>
<NavLink style={{ color: 'white' }} to={`activities/${item.id}`}>
{item.name}
</NavLink>
<LikeBtn />
</li>
))}
</ul>
</>
);
}
There is also a snippet below that you can run:
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
search: '',
};
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
let filteredList = this.state.search
? this.props.listProp.filter((item) =>
item.name.toLowerCase().includes(this.state.search.toLowerCase())
)
: this.props.listProp;
return (
<React.Fragment>
<input type="search" name="search" autocomplete="off" onChange={this.handleChange} />
<ul>
{filteredList.map((item) => (
<li className="listItem" key={item.id}>
<a href={`activities/${item.id}`}>{item.name}</a>
<button>Like</button>
</li>
))}
</ul>
</React.Fragment>
);
}
}
const data = [
{
id: 1,
name: 'Congress, The',
},
{
id: 2,
name: 'Glen or Glenda',
},
{
id: 3,
name: "Don't Drink the Water",
},
{
id: 4,
name: 'Blind',
},
{
id: 5,
name: 'Sirocco',
},
{
id: 6,
name: 'Sunset Strip',
},
{
id: 7,
name: 'Better Living',
},
{
id: 8,
name: '4:44 Last Day on Earth',
},
{
id: 9,
name: 'The Heavy',
},
{
id: 10,
name: 'Dr. Who and the Daleks',
},
{
id: 11,
name: 'Legend of Hell House, The',
},
{
id: 12,
name: 'Exit Humanity',
},
{
id: 13,
name: 'Young in Heart, The',
},
{
id: 14,
name: 'Soul Kitchen',
},
{
id: 15,
name: 'Accattone',
},
];
ReactDOM.render(<SearchForm listProp={data} />, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can move this part
let list = this.props.listProp.map(item => <li className="listItem" key={item.id}><NavLink style={{ color: 'white' }} to={`activities/${item.id}`}>{item.name}</NavLink><LikeBtn /></li>)
to the return and filter the listProp on handleChange.
You can refer to this codeSandbox here for a working sample
when ever i try to select an option in input field it must set the state value to the selected option but it return undefined
I am using Semantic ui react Form to take input but when ever i select the option and submit it gives me undefined
import React from 'react'
import { Form, Input, TextArea, Button, Select, Container } from
'semantic-ui-react'
const RankOptions = [
{ key: 'lg', text: 'Lt-Gen', value: 'Lt-Gen' },
{ key: 'mg', text: 'Mj-Gen', value: 'Mj-Gen' },
{ key: 'b', text: 'Brig', value: 'Brig' },
{ key: 'col', text: 'Col', value: 'Col' },
{ key: 'lc', text: 'Lt-Col', value: 'Lt-Col' },
{ key: 'm', text: 'Major', value: 'Mj' },
{ key: 'capt', text: 'Capt', value: 'Capt' },
{ key: 'lt', text: 'Lt', value: 'Lt' },
{ key: '2lt', text: '2-Lt', value: 'Lt-2' },
]
export default class Employee extends React.Component{
state={}
handleSubmit = () => {
console.log(this.state)
}
handlerankChange = (e) => {
const value = e.target.value
this.setState({
rank : value
})
}
render() {
return (
<Container>
<Form size='huge'>
<Form.Group widths='equal'>
<Form.Field
name = 'rank'
control = {Select}
label = 'Rank'
options = {RankOptions}
placeholder = 'Rank'
value = {this.state.value}
onChange = {this.handlerankChange}
/>
<Button primary onClick=
{this.handleSubmit}>Submit</Button>
</Form>
</Container>
)
}
}
the state must be any option from ranks
A working code will help you out:
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import {
Button,
Form,
Grid,
Header,
Image,
Message,
Segment,
Label,
Dropdown
} from "semantic-ui-react";
import Select from "react-select";
import "./index.css";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
class App extends React.Component {
state = {
selectedOption: ""
};
handleChange = selectedOption => {
this.setState({ selectedOption });
};
render() {
const { selectedOption } = this.state;
const value = selectedOption && selectedOption.value;
return (
<div className="login-form">
<Grid
textAlign="center"
style={{ height: "100%" }}
verticalAlign="middle"
>
<Grid.Column style={{ maxWidth: 450 }} textAlign="left">
<Form size="large">
<Segment>
<div>
<Select
name="form-field-name"
value={value}
onChange={this.handleChange}
options={[
{ value: "one", label: "One" },
{ value: "two", label: "Two" }
]}
/>
</div>
</Segment>
</Form>
</Grid.Column>
</Grid>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Source of the code on the codesandbox
Set initial value for rank in state as
state = {
rank:''
}
and change
<Form.Field
name = 'rank'
control = {Select}
label = 'Rank'
options = {RankOptions}
placeholder = 'Rank'
value = {this.state.rank}
onChange = {this.handlerankChange}
/>
you need not access the value by e.target.value, the callback provides object with key 'value';
eg:
import React from 'react'
import { Form, Input, TextArea, Button, Select, Container } from
'semantic-ui-react'
const RankOptions = [
{ key: 'lg', text: 'Lt-Gen', value: 'Lt-Gen' },
{ key: 'mg', text: 'Mj-Gen', value: 'Mj-Gen' },
{ key: 'b', text: 'Brig', value: 'Brig' },
{ key: 'col', text: 'Col', value: 'Col' },
{ key: 'lc', text: 'Lt-Col', value: 'Lt-Col' },
{ key: 'm', text: 'Major', value: 'Mj' },
{ key: 'capt', text: 'Capt', value: 'Capt' },
{ key: 'lt', text: 'Lt', value: 'Lt' },
{ key: '2lt', text: '2-Lt', value: 'Lt-2' },
]
export default class Employee extends React.Component{
state={}
handleSubmit = () => {
console.log(this.state)
}
handlerankChange = ({ value }) => {
this.setState({
rank : value
})
}
render() {
return (
<Container>
<Form size='huge'>
<Form.Group widths='equal'>
<Form.Field
name = 'rank'
control = {Select}
label = 'Rank'
options = {RankOptions}
placeholder = 'Rank'
value = {this.state.rank} // this should be rank
onChange = {this.handlerankChange}
/>
</Form.Group>.
<Button primary onClick=
{this.handleSubmit}>Submit</Button>
</Form>
</Container>
)
}
}
Hope this helps!!
I have a dropdown list with 5 options. I need to save the selected option to my state as listValue.
My list of options and the state
const options = [
{ key: 1, text: 'OK', value: 1 },
{ key: 2, text: 'Avvikelse', value: 2 },
{ key: 3, text: 'Ej Relevant', value: 3 },
{ key: 4, text: 'Observation', value: 4 },
{ key: 5, text: 'Saknas', value: 5 },
]
export default class ConfirmationModal extends React.Component {
state = {
listValue: 'Status'
}
My list (from semantic-ui)
dropDownList = () => (
<Dropdown
placeholder={this.state.listValue}
clearable
options={options}
selection
/>
)
How can I store the selected option in my state?
You can add an onChange handler and put the value given to the handler in your component state.
Example
const options = [
{ key: 1, text: "OK", value: 1 },
{ key: 2, text: "Avvikelse", value: 2 },
{ key: 3, text: "Ej Relevant", value: 3 },
{ key: 4, text: "Observation", value: 4 },
{ key: 5, text: "Saknas", value: 5 }
];
class DropdownExampleControlled extends React.Component {
state = {
options,
value: options[0].value
};
handleChange = (_e, { value }) => this.setState({ value });
render() {
const { value, options } = this.state;
const currentOption = options.find(o => o.value === value);
return (
<Grid columns={2}>
<Grid.Column>
<Dropdown
onChange={this.handleChange}
options={options}
placeholder="Choose an option"
selection
value={value}
/>
</Grid.Column>
<Grid.Column>
<Segment secondary>
<pre>Current value: {currentOption.text}</pre>
</Segment>
</Grid.Column>
</Grid>
);
}
}
As I understood you, you need to save in the state the values, which user selected?
If yes, You need have an event for example onChange, which means that user seelct that particular option from list. and set it in state
onChange(selectedValue) {
this.setState({listValue: selectedValue});
}
add this function to your component:
handleChange = (_p, { value }) => {
this.setState({ listValue: value});
};
add it as prop to your Dropdown:
<Dropdown onChange={this.handleChange} placeholder={this.state.listValue} clearable options={options} selection />
Handle state management using setState. Simple example:
Example Sandbox
const options = [
{ key: 1, text: 'OK', value: 1 },
{ key: 2, text: 'Avvikelse', value: 2 },
{ key: 3, text: 'Ej Relevant', value: 3 },
{ key: 4, text: 'Observation', value: 4 },
{ key: 5, text: 'Saknas', value: 5 },
]
class App extends Component {
constructor(props){
super(props)
this.state = {
listValue: ''
}
}
componentWillMount() //before render
{
this.setState({
listValue: options[1].text //storing text from second line
})
}
render() {
return (
<div>
{this.state.listValue}
</div>
);
}
}
This displays: Avvikelse