Dropdown list not showing default item - reactjs

I am using the semantic-ui-react dropdown list, which I have working just fine. The problem is, on my form I am pulling data from a database using the Mobx store. I have a array setup for the options in the dropdown list. when the form loads from the store the text field for the dropdown list is blank, if I click on the dropdown I can see that the selected option is highlight (bold). How do I get the text field to show the default options. I have included some code below if anyone can look at it and give me an idea of what I need to do.
Thanks for all your help.
Here is the code for the dropdown list:
<div className="col-sm-3">
<div className="bg-primary text-white text-center">
Driver
</div>
<div>
<Dropdown
selection
fluid
id="driver"
name="driver"
ref="driver"
onChange={this.handleChange}
value={this.props.EquipmentStore.truck_detail.driver}
options={this.props.EquipmentStore.driver_list}/>
</div>
</div>
Here is how I am building the driver_list, I am basically getting a list of users from the database and create an array with value and text fields
let newUserItem = {
value: getUser.id,
text: getUser.first_name + " " + getUser.last_name
};
this.driver_list.push(newUserItem)
The value in the truck_detail.driver is a numberic value that the same value in the value field in the driver_list value field...that is all working fine, I can not get the text value to show in the text field for the dropdown list by default.
Here is the code that I use to build the options list:
async loadDriverList() {
let endpoint = '/api/users/profile/?owner=True';
this.driver_list.length = 0;
let lookupOptions = {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
};
try {
const response = await fetch(endpoint, lookupOptions);
const profile_list = await response.json();
const userItem = {value:0, text:'Select Driver'};
this.driver_list.push(userItem);
let array_length = profile_list.length;
for (let i = 0; i < array_length; i++) {
let ownerId = profile_list[i].user;
let endpoint = '/api/users/users/' + ownerId + '/';
let userList = await fetch(endpoint, lookupOptions);
let getUser = await userList.json();
let newUserItem = {
value: getUser.id,
text: getUser.first_name + " " + getUser.last_name
};
this.driver_list.push(newUserItem)
}
} catch(e) {
console.log(e)
}
}

After a lot of conversation with Predrag Beocanin I have solved this issue. What it boils down to is my form (with the Dropdown) was getting render before the options list was fully populated. In my application I have a form that shows a list of items, once you click on the item it will render a detailed form of that listed item. Originally I wall trying to populate my options list once you click on the item you wanted to view the details on. Because the options list is basically a static list, I am now populating that list when you are view the first form. Now when you click on the item to view the Dropdown options are fully populated and working just as I had expected.
Thanks for your help Predrag.

Related

How can I create a parent html element by appending sub element from an object?

In my react app I need to return a line which will be created based on a list.
Here is the object,
searchCriteria: {
op_company: "039",
doc_type: "ALL"
}
and in my UI, i need to show it as a paragraph with bold values. So the hard coded code would be like below
<p>Download request for op_company: <b>{searchCriteria.op_company}</b>, doc_type: <b>{searchCriteria.doc_type}</b></p>
But the object(searchCriteria) will be changed based on the user request. So I tried like below.
const getSearchCriteria = (criteria) => {
let searchCriteria = []
searchCriteria.push('Download request for')
Object.keys(criteria).forEach((key) => {
if(criteria[key] !== '') {
searchCriteria.push(` ${key}: ${criteria[key]},`)
}
});
return searchCriteria;
}
return (
<p>
{getSearchCriteria(searchCriteria).map((item) => <span key = {item}>{item}</span>)}
</p>
);
here i'm getting the expected output. But I can't get the value as bold (highlighted). Is there another way to directly deal with html elements?

Retrieve ID after pushing to SharePoint list using React PNPJs

I'm building a SharePoint SPFx react app. In a nutshell, the user fills out a form that I created. When the user hit's submit, using PNPJs: https://pnp.github.io/pnpjs/sp/items/ I'm adding the item to a list called Request.
From there I want to send an email that contains the URL link to that item they created. Right now, my code adds the item to the list and I'm able to send an email with no problem. However, I want to get the ID of the item that was just added to the list, so that I can add it to the email.
Here is a striped down snippet of my function that adds items to the Request list.
async submitNewRequest():Promise<any> {
let preprocessedData;
try {
// add an item to the list
pnp.sp.web.lists.getByTitle("Requests").items.add({
Title: this.state.Title,
Requestor_x0020_Email: this.state.getEmail,
Created: this.state.startDate,
}).then((iar) => {
console.log(iar);
//Is this where I would get the ID
});
const emailProps: EmailProperties = {
To: [this.state.getEmail],
Subject: "Your court requisition has been submitted.",
Body: this.initalMessage
};
} catch(error) {
}
return preprocessedData;
}
I believe what I have to do is in the .then((iar) => { when item is successfully added to the list, to get a response back with that item ID. But I'm not sure how. In my const emailProps: EmailProperties is where I'm sending the email, which again works.
Typically I can do something like this await sp.web.lists.getByTitle("Request").items.getById(1).get(); and in the console I will get back something like this:
0:
Title: "My title here"
Description: "Description Here"
ID: 24
Here is on submit function:
async _onNewRequest(event) {
event.preventDefault();
await this.submitNewRequest();
this.displayPop();
}
And lastly my email function:
get initalMessage() {
return `<p>This is my email template that I stripped down.</p>
<p>
<a href="https://mywebsite.sharepoint.com/sites/Requests/SitePages/Home.aspx#/MyRequests/'+ NEED_ID_HERE +'" target="_blank">
Click Here
</a>
</p>`;
You could retrieve the Id of the item like this:
sp.web.lists.getByTitle("ct0").items.add({
Title:"test"
}).then(iar=>{
console.log(iar.data.ID);
})
The code would be like this:
const iar=await sp.web.lists.getByTitle("ct0").items.add({
Title:"test"
});
const id=iar.data.ID;
const emailProps: EmailProperties = {
To: [this.state.getEmail],
Subject: "Your court requisition has been submitted.",
Body: this.initalMessage,
ID:id
};

Angular 6 dynamic checkboxes keyvalue return array of IDs

I have a list of dynamic checkboxes using keyvalue pipe that returns objects rather than just array of selected IDs.
can anyone help pls, I need the form to submit just an array of selected user IDs.
https://stackblitz.com/edit/angular-ciaxgj
EDIT
here's the log of a similar form with a multi-select (countries):
console log
I need users (checkboxes) to return an array like countries (multi-select) as in the log above.
Change your OnSubmit function to
onSubmit() {
console.log(this.userForm.value);
var usersObj = this.userForm.value.users;
var selectedUserIds = [];
for (var userId in usersObj) {
if (usersObj.hasOwnProperty(userId)) {
if(usersObj[userId])//If selected
{
selectedUserIds.push(userId);
}
}
}
console.log(selectedUserIds);
}
Here is updated code
https://stackblitz.com/edit/angular-9fd17t
If you want to submit as a Form then add a hidden field to form
<input type="hidden" name="selectedUserIds" value=""/>
set value selectedUserIds from onSubmit and submit the form code.
So, it happens that I have been overthinking the solution in thinking that like the multiselect, checkboxes would/could return a ready array of selected items.
The rather simple solution was from reading another of Eliseo's posts combined with Jaba Prince's answer:
onSubmit() {
var usersObj = this.userForm.value.users;
var selectedUserIds = [];
for (var userId in usersObj) {
if (usersObj.hasOwnProperty(userId)) {
if(usersObj[userId])//If selected
{
selectedUserIds.push(userId);
}
}
}
let data = {
users: selectedUserIds
}
console.log(data);
// post data in service call
}
Many thanks to you two!

React, dynamically add text to ref span

I'm trying to render a message to a span tag specific to an item in a list. I've read a lot about React 'refs', but can't figure out how to populate the span with the message after it's been referenced.
So there's a list of items and each item row has their own button which triggers an API with the id associated with that item. Depending on the API response, i want to update the span tag with the response message, but only for that item
When the list is created the items are looped thru and each item includes this
<span ref={'msg' + data.id}></span><Button onClick={() => this.handleResend(data.id)}>Resend Email</Button>
After the API call, I want to reference the specific span and render the correct message inside of it. But I can't figure out how to render to the span at this point of the code. I know this doesn't work, but it's essentially what I am trying to do. Any ideas?
if (response.status === 200) {
this.refs['msg' + id] = "Email sent";
I recommand using state. because string refs legacy (https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)
const msgs = [
{ id:1, send:false },
{ id:2, send:false },
{ id:3, send:false },
];
this.state = {
msgs
};
return this.state.msgs.map((msg, index) => {
const status = msg.send ? "Email Sent" : "";
<span>{ status }</span><Button onClick={() => this.handleResend(index)}>Resend Email</Button>
});
async handleResend (index) {
const response = await callAPI(...);
if(reponse.status !== 200) return;
const newMsgs = _.cloneDeep(this.state.msgs);
newMsgs[index].send = true;
this.setState({
msgs: newMsgs
})
}
The workaround is set innerText
this.refs['msg' + id].innerText = "Email sent";
But rather than using ref try to use state to update elements inside render.
i was facing with this issue right now and i figured it out this way:
// currentQuestion is a dynamic Object that comes from somewhere and type is a value
const _target = `${currentQuestion.type}_01`
const _val = this[`${_target}`].current.clientHeight // here is the magic
please note that we don't use . after this to call the ref and not using refs to achieve what we want.
i just guessed that this should be an Object that would hold inner variables of the current object. then since ref is inside of that object then we should be able to call it using dynamic values like above...
i can say that it worked automagically!

react-native-multiple-select storing items selected on submit

I am using react-native-multiple-select and trying to create a dropdown menu that allows users to select multiple options and then logs the options they select into an array.
At the moment, my code is:
onSelectedItemsChange = selectedItems => {
this.setState({ selectedItems });
console.log('submit button was pressed')
};
render() {
const { selectedItems } = this.state;
return (
<View style={{ flex: 1 }}>
<MultiSelect
hideTags
items={items}
uniqueKey="id"
ref={(component) => { this.multiSelect = component }}
onSelectedItemsChange={this.onSelectedItemsChange}
selectedItems={selectedItems}
selectText="Pick Items"
searchInputPlaceholderText="Search Items..."
onChangeInput={ (text)=> console.log(text)}
altFontFamily="ProximaNova-Light"
tagRemoveIconColor="#CCC"
tagBorderColor="#CCC"
tagTextColor="#CCC"
selectedItemTextColor="#CCC"
selectedItemIconColor="#CCC"
itemTextColor="#000"
displayKey="name"
searchInputStyle={{ color: '#CCC' }}
submitButtonColor="#CCC"
submitButtonText="Submit"
/>
<View>
The problem is with the submit button. I only want to record the items selected once the user has pressed submit.
At the moment it logs that the button was pressed every time a new item is selected and that does not help with storing the items selected into another array.
Any help would be great.
You can do this to get an array with the item objects that are selected:
for(var i = 0; i < selectedItems.length; i++){
this.state.selectedItemsArray.push(this.state.gasOptions[selectedItems[i]])
}
console.log(selectedItems);
This should output the array of items that are selected with each item containing the unique key and the display name.
this.state.selectedItemsArray.push(listOfObject[0].id);
I noticed that the selectedItemsArray stores only the key so its an array of keys and not list of objects. Thus, if your key is id you want to push that to the array and not all the object.
I faced the same issue before. Now I fixed it.
Follow below steps:
Go to node_modules/react-native-multi-select/index.d.ts add the code
onSubmitclick: ((items: any[]) => void), inside export interface MultiSelectProps {}
Go to lib/react-native-multi-select.js add the code
onSubmitclick: PropTypes.func, inside the static propTypes ={}
Go to the function _submitSelection() and add the code inside it
const {selectedItems, onSubmitclick } = this.props; onSubmitclick(selectedItems);
Now you return your Multiselect tag add
onSubmitclick={(value1) => getSubmit(value1)}
capture your selected value with this function
const getSubmit = (value1) => { console.log('new submit value***', value1) }
I hope, It will helpful for someone.

Resources