DropDown menu is not showing values of the passed array - reactjs

The values of skillList is not showing in the drop down.it shows an empty dropdown.(the data fetched from api is pushed into the skillList array without any issue)
import React, { Component } from 'react'
let skillList = [];
export class DataCheck extends Component {
constructor(props) {
super(props)
this.state = {
skill: "",
skillId: "",
}
this. handleSkillChange=this. handleSkillChange.bind(this);
}
componentDidMount() {
// worker skill selection
fetch("http://localhost:3001/dataservices/getallskills")
.then (res=>res.json())
.then(res => {
console.log(res);
let temArray = {};
for (let i = 0; i < res.recordsets[0].length; i++) {
temArray["value"] = res.recordsets[0][i].SkillId;
temArray["label"] = res.recordsets[0][i].SkillTitle;
skillList.push(temArray);
console.log(skillList);
temArray = {};
}
})
.catch(function(error) {
console.log(error);
});
}
handleSkillChange(skill) {
this.setState({
skill: skill,
skillId: skill.value
});
}
render() {
return (
<div>
<form>
<select
value={this.state.skill}
onChange={this.handleSkillChange}
options={skillList}
placeholder="Skills"
/>
</form>
</div>
)
}
}
export default DataCheck
when I check the dev-tools, it shows like this:
options:Array
0:Object
label:"wood works"
value:6
(Array consists of 16 objects like this)
console says:
warning.js:36 Warning: Unknown prop options on tag. Remove this prop from the element.

Native select does not have an options props. You have to manually map the option tag:
<select
value={this.state.skill}
onChange={this.handleSkillChange}
placeholder="Skills"
>
{this.state.skillList.map((optionSkill) => (
<option value={optionSkill.value}>{optionSkill.label}</option>
)}
</select>
Currently you have added skillList as a normal variable with module scope. Even though you have changed skillList, the same will not be reflected in the UI because React does not detect this change. you will have to change skillList to a state variable for React.
this.state = {
skill: "",
skillId: "",
skillList: []
}
fetch("http://localhost:3001/dataservices/getallskills")
.then (res=>res.json())
.then(res => {
this.setState({
skillList: res.recordsets[0].map((recordSet) => ({
label: recordSet.SkillTitle,
value: recordSet.SkillId,
}))
});
});

You have to add option tag inside select. Loop array of items using .map and you will get your result.
This codepen can help you to make this work,
select example
Hope this can help you!

Related

How to filter data from an object array according to their property values, in ReactJs?

I wrote a simple code to just pass all the data taken from a firebase real time database into a react component, which is called cubetemplate, via an object array. Here is a screenshot of the firebase I used to do the test:
Here's the code I used:
<div className="gal">
{Object.keys(this.state.gallery)
.sort()
.map(item => {
//inserting into the component
return <Cubetemplate source={this.state.gallery[item]["img"]} key={item}/>;
})}
</div>
Now, the problem is that, I want to pass only the objects which verify the condition "type"="vid", into the Cubetemplate component. How do I accomplish this?
Here's the full code to take a better understanding of the situation:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Cubetemplate from './components/cubes/Cubetemplate';
import './Gallery.css';
import * as firebase from 'firebase';
class Gallery extends Component {
//this is the place where you declar your vars
constructor(props) {
super(props);
this.state = {
loading: false,
list: [1, 2, 3],
value: '',
gallery:{},
isLoggedIn: false,
};
this.readDB = this.readDB.bind(this); //no idea what the hell this is
}
readDB() {
var that = this;
var starCountRef = firebase.database().ref("/gallery");
//the values from the firebase will be printed in the console
starCountRef.once('value', snapshot => {
snapshot.forEach(function (childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
console.log("Key: " + childKey + " Title: " + childData.title);
});
that.setState({ isLoggedIn: true });
//just to check the values of snapshot
// console.log(snapshot.val());
//takes the data from friebase to snapshot to news.
this.setState({ gallery: snapshot.val() });
console.log(this.gallery);
}, err=> {
//errors
console.log(err);
});
};
componentDidMount(){
this.readDB();
};
render() {
return (
<div className="gallerycontainer">
<div className="gal">
{Object.keys(this.state.gallery)
.sort()
//map
.map(item => {
//inserting into the component
return <Cubetemplate source={this.state.gallery[item]["img"]} key={item}/>;
})}
</div>
</div>
);
}
}
export default Gallery;
Thanks in advance stackoverflowers!
You could use firebase filtering like Frank mentioned or you could simply do some conditional rendering like this:
<div className="gal">
{Object.keys(this.state.gallery)
.sort()
.map(item => {
//Only render if the item type is 'vid'
if (this.state.gallery[item]["type"] == "vid") {
<Cubetemplate source={this.state.gallery[item]["img"]} key={item}/>;
}
})}
</div>
To load only the gallery child nodes with type equal to vid, you'd use a Firebase query like this:
var galleryRef = firebase.database().ref("/gallery");
var query = galleryRef.orderByChild("type").equalTo("vid");
query.once('value', snapshot => {
...
For more on this, I highly recommend studying the Firebase documentation on ordering and filtering data.

I wanna console.log the value after clicking the submit button once and to delete the previous mapped items, but it doesnt work

I'm very new to react and I got two problems:
I want to console log the input and display the mapped data after clicking the submit button once. But I get console logged the input and the mapped data after clicking the button twice.
I wanna clear the mapped list (data from previous input) and display new list items depending on the input. But the new list items are only added to the end of the previous list (only the last list item from the previous list got overwritten by the first list item of the new list).
So this is the code from my app component:
import React, { Component, Fragment } from 'react';
import './App.css';
import Display from './/Display';
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
passedValue: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
this.setState({ passedValue: this.state.value });
console.log(this.state.passedValue);
event.preventDefault();
}
render() {
return (
<div>
<form className="inputContainer" onSubmit={this.handleSubmit}>
<input type="text" name="company_name" onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
<Display listDataFromParent={this.state.passedValue} />
</div>
);
}
}
export default App;
And this is my display component:
import React, { Component } from 'react'
import "./Display.css";
export default class Display extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
data: []
};
}
componentWillReceiveProps() {
fetch("http://localhost:5000/company?company_name=" + this.props.listDataFromParent)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
data: result
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, data } = this.state;
// if (error) {
// return <div>Error: {error.message}</div>;
// } else if (!isLoaded) {
// return <div>Loading...</div>;
// } else {
return (
<div className="display">
<h1>Kreditnehmer</h1>
<ul>
{this.props.listDataFromParent}
{data.map(item => (
<li key={item.c.company_id}>
Relation type: {item.r.relation_group}
Last name: {item.p.last_name}
</li>
))}
</ul>
</div>
);
}
}
Can anyone help?
1) setState is async method in react means it will take some time to update the component state. You can get your console log by using callback function of setState like
this.setstate({ value: e.target.value }, () => { console.log(this.state.value) });
2) in display component, your using componentWillReciveProps life cycle and inside that your using this.props.listdatafromparent which is pointing previous props. Rather than using this.props I would suggest consider props param of life cycle, means it should be like
componentWillReciveProps(props) {
// your code
Console.log(props.listdatafromparent);
}
The handleSubmit method is wrong... the console log is executed before the state is changed. You need to put it inside a callback function as a second parameter of setState.
this.setState({ passedValue: this.state.value }, () => {
console.log(this.state.passedValue);
});
Answers are:
1) Callback function should be used on setState, in order to do console.log after state is really updated.
In your case you call setState and setState is async function, which means that console.log won't wait until state is really updated.
Your code should be:
handleSubmit(event) {
this.setState({ passedValue: this.state.value },
() => console.log(this.state.passedValue));
event.preventDefault();
}
2) I would move data fetching out of componentWillReceiveProps(), since this lifecycle method will be deprecated from version 17 and it is fired on every render(). Try replacing with componentDidMount() or componentDidUpdate(). Maybe just this small change will solve your problem. If not pls post results and I will take a look again.

Using HTML Selectors with React

I'm trying to use the select tag in React. I have the following component:
class InteractionHeader extends React.Component {
constructor(props) {
super(props);
this.state = {
allDays: [],
selected: ""
};
this.dateChanged = this.dateChanged.bind(this);
}
componentDidMount() {
this.setState({
allDays: ["a", "b"],
selected: "a"
});
}
dateChanged(e) {
e.preventDefault();
console.log(event.target.value);
}
}
And in my render, I have the following:
render() {
return (
<div>
<select value={this.state.selected} onChange={this.dateChanged}>
{this.state.allDays.map((x) => {
return <option key={`${x}`} value={`${x}`}>{x}</option>
})};
</select>
</div>
);
}
However, when I select a different option, my console prints undefined instead of the option I selected. What is going on and how do I prevent it?
You are calling it wrong
dateChanged(e) {
console.log(e.target.value);
}
You should use prevent default in case where you donot want your page to take a refresh and try to make a server side call. In case of select there is nothing like this.
You have a typo in dateChanged(e) method. You need to log e.target.value instead of event.target.value.

ComponentDidMount Updates State, but doesnt seem to re-render component

The problem I face is that it doesn't seem that componentDidMount is re-rendering my component, even though it is updating the state. Lot of code coming up, but it gives context to the issue I'm having. If I need to, I can upload screenshots of what is happening.
Here's the constructor:
export class Upload extends React.Component<RouteComponentProps<{}>, UploadTaggingOptions> {
constructor(props: any) {
super(props);
this.state = {
photographer: [
{ id: null, value: '', label: '' },
],
};
}
Here's component did mount:
componentDidMount {
//Fetch request for photographers from the db
fetch("http://localhost:49775/api/photographers")
.then(res => res.json())
.then((result) => {
var photographerData = this.state!.photographer;
var y = 0;
//Remove the empty object first and foremost. The list should now be totally empty
photographerData.shift();
//The loop to add the galleries to the galleryData array
for (var i in result) {
var id = result[i].id;
var value = result[i].firstname + ' ' + result[i].lastname;
var label = value;
var photographer = { "id": id, "value": value, "label": label };
photographerData.push(photographer);
y++;
}
this.setState({
isLoaded: true,
photographer: photographerData
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
alert("Error loading options for the photographers. Refresh the page. If the error persists, please contact your administrator");
}
)
And finally Render:
public render() {
return <div>
<div className="photographers">
<p><b>Photographer:</b></p>
<DropDown options={this.state!.photographer} />
</div>
}
Just for clarity's sake, there are more components on the screen (hence the extra div for the dropdown component).
I'm not sure why, but the dropdown renders with the blank options I intitialize in the constructor, componentdidupdate does the fetch request AND updates the state to the data that was fetched, but I have to click the blank value in order to load those data values into the dropdown. It is almost like it re-renders after I change the selected value instead of on state change.
I've tried moving those requests into the constructor, but have the same problem. Perhaps
EDIT: Here's the code for the Dropdown component:
import * as React from 'react';
import Select from 'react-select';
const DropDown = (props: any) => {
return (
<div className="dropdown">
<Select
closeOnSelect={!(props.stayOpen)}
disabled={props.disabled}
options={props.options}
placeholder="Select an option..."
removeSelected={props.removeSelected}
simpleValue
value={props.selectedPhotographer}
searchable={true}
multi={true}
/>
</div>
)
}
export default DropDown;
From react official documentation:
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
But in your code you are mutating it, albeit via an assignment to another variable:
var photographerData = this.state!.photographer;
// this DOES mutate the original array.
photographerData.shift();
This can mess with Reacts batching update strategy and can cause delays.
If you do not need the data from original state, you can just do:
var photographerData = [];
window.onload = function() {
console.log('Testing');
let testArr1 = [1, 2, 3]
console.log('TestArr1 length before shift: ' + testArr1.length);
let testArr2 = testArr1;
testArr2.shift();
console.log('TestArr1 length after shift: ' + testArr1.length);
}

Reactjs Select v2 - How to handle Ajax Typing?

I am using reactjs select 2 but I don't know how to make it work so that when a user types something in a ajax request is made and the results are sent back.
I see it has some async options but I don't get how it works and how I would get it to work with axios.
I come up with this but it is kinda laggy when a user types(probably because it is re-rendering it after each type) and when the user selects a choice the value disappears.
export default class TestComponent extends Component {
constructor(props) {
super(props);
this.state = {value: ""};
}
onInputChange(option) {
this.getOptionsAsync(option)
}
getOptionsAsync(newInput) {
var that = this;
console.log("ffd", newInput)
axios.get(`https://localhost:44343/api/States/GetStatesByText?text=${newInput}`)
.then(function (response) {
var formatedResults = response.data.map((x)=> {
return {value: x.id, label: x.name}
})
that.setState({
options: formatedResults,
value: newInput
})
})
.catch(function (error) {
});
}
render() {
console.log(this.state.value, "value")
return (
<div className="test">
<Select
onInputChange={this.onInputChange.bind(this)}
value={this.state.value}
options={this.state.options }
/>
</div>
);
}
}
You're going to be doing an api call every single time that you type a letter with the current way you're doing things. I would recommend just loading the states once at the beginning, perhaps in your ComponentDidMount() method.
If you pass the isSearchable prop to React-Select it will automatically work as a filter anyways.
Another thing I've had to do in this case which I believe will fix your change problem is to make sure it calls the handler on change not just on input change.
Pass this prop:
<Select
value={this.state.value}
options={this.state.options }
onChange={value => {
if (value) this.onInputChange(value)
else this.onInputChange('')
}
/>
Due to the way this is automatically bound to arrow functions, you won't have to bind to this if you change your onInputChange to the following:
onInputChange = (value) => {
this.getOptionsAsync(value)
}
Finally, you should be setting the state in the above function so the value is stored.
onInputChange = (value) => {
this.getOptionsAsync(value)
this.setState({value})
}

Resources