Get data from dynamic form in React - javascript

I have some troubles getting data from a form in react. The form itself is dynamic, meaning that some of my fields aren't always there, but only rendered in specific cases.
When attaching these its hard to anticipate how the state of the container should look. And also which handleChange functions should be there. The components in my form are 2 levels deep at least, so the component is in itself rendering the final input component to the DOM.
Did some looking and found that people have been using refs, but there is a lot of negative opinions about this approach. And it does seem kinda... Fiddly.
Question:
How could you go about getting all the data from a form when its dynamic?
The setup:
<Form onSubmit={this.acceptOffer.bind(this)}>
<MainProductContainer offer={this.state.offer}/>
<RequirementsContainer requirements={this.state.offer.requirements}/>
<Segment basic textAlign='center'>
<Button
type='submit'
content='Send'
primary
loading={this.state.accept_state == 'pending'}>
</Button>
</Segment>
.
acceptOffer(event) {
//This is where I want to get all the data from the form
}

Here you can find how to do it: React Native how to pass this.setState change to parent

Related

React Handle multiple forms within a parent component

I have a page with dynamic tabs and each of them have a form input. There is a common Submit for each of these forms. As of now, I have a separate component for each of the forms and each of them have multiple user inputs.
<div id="#parentComponent">
{myForm1 && <div><MyForm1 {...props}/></div>}
{myForm2 && <MyForm2 {...props} /></div>}
<div>
<input type="submit">
Now, my question is on Submit (common and in the parent component), I want to be able to access each of the form input values. But as of now, my inactive tab/component gets destroyed and only the active tab/component is there in the DOM.
What is the best way to handle this? Also should there be any preference to controlled/uncontrolled components to handle this use case ?
As of now, I am using the uncontrolled form for these form inputs (using the useformcontext)
I would keep the state in a higher order component, and update it by any change withing the forms.
I would pass down a setFormsData function to every form, and add their data on every change, keeping the old state, like this:
const handleOnChange = value => setFormsData(oldFormData => {...oldFormData, ...value})
You can also use a redux store if you wish.

Setting the boolean value of aria-expanded using React Hooks

I'm currently working on accessibility in a web application using React & Ant Design's Select component. aria-expanded is set to false string.
I want to use React useState to toggle aria-expanded="false" so that the aria label in the screen reader can read back wether the dropdown is open or closed.
The idea is to take the default state and use it in the useState hook like this:
const [selectAria, setSelectAria] = useState('false');
<Select
name="someName"
id="someID"
onSelect={(value) => handleChangeSelect(value)}
aria-label={
selectAria ? 'i am closed' : 'i am open '
}
aria-expanded={selectAria}
>
The screen reader is only able to recognize when the initial state. After I select an option, and the dropdown is closed, it does not read back the new state.
Is it possible to do this in React hooks? Is it possible to access the aria-expanded attribute in useState along with the boolean value? I haven't worked on advanced accessibility and have to stick with the antD library for this. Thanks in advance.
In Ant Design, they have provided a bunch of props with very simple names to get our things done in a very friendly manner.
You can decide the initial openness/closeness of your Select element using defaultOpen prop and, always one-to-one bound openness/closeness using open prop.
Here you want to control the open/close action in always one-to-one bound manner I guess. So your code should be like this!
const [selectAria, setSelectAria] = useState(false);
<Select
name="someName"
id="someID"
onSelect={(value) => handleChangeSelect(value)}
open={selectArea}
>
*Note: Removed your aria-label attribute as well. Refer official AntD documentation for a suitable prop API - Select Component!
**Note: If you use this open prop I mentioned above, it may never allow you to close the panel until your selectAria variable is true. So you have to carefully handle that situation as well!
***Note: This answer is referred to Ant Design version 4.7.3. Select the correct version of documentation before you refer!

Performance Issue On Render In ReactJS

From what I'm reading, desired practice for working with form elements and state update is following:
onChange = (event) => {
this.setState({
name:event.target.value
})
}
where above is event handler for a input field:
<input
type="text"
onChange={this.onChange}
value={this.state.name}
/>
And this is how we keep state updated, and also input field itself.
Now if we put a console.log(new Date()) inside render function, we can observe that render is called on each key press in input field.
My question is, can this cause a performance issue, actually if there are known cases when this can cause performance issue?
Also, isn't there any better way, this updating-state-re-rendering doesn't seem to be most efficient?
Edit 1: Imagine complex form control, lots of complex form items that can be further more complex controls,... So this input is inside of this complex component that is timely to render. Now, can you expect(did ever happened to you), that re-rendering on state update(while typing) to cause performance issue (visible lag).
This is how React is built. See official doc.
You can use web inspector and type to check what’s being re-rendered and that’s only the text input box.
Yes it gets called every time you type, but only what’s being changed actually re-renders.

Lightning Component, retrieving lookup record values in controller

I'm trying to convert a simple OnClick Javascript button to Lightning. This OnClick is pretty simple, it just opens a URL, but it uses a value on a parent record as part of the URL. ie, a button on the Opportunity Object that will grab part of the URL from it's parent Account's This_Field__c field:
window.open('https://www.salesforce.com/'+'{!Account.This_Field__c}'+'/info');
So if the value on the field was XYZ, this would open the page https://www.salesforce.com/XYZ/info
What's the easiest way to get the value of Account.This_Field__c in a lightning component?
Considered using an Apex controller but that seems like overkill. Tried force:recordData, didn't seem to work, possibly because of it beign on a parent record. We don't want more fields on the Opportunity, otherwise I might try a formula.
window.open('https://www.salesforce.com/'+'{!Account.This_Field__c}'+'/info');
If the value on the field was XYZ, this would open the page https://www.salesforce.com/XYZ/info
<force:recordData> does support relationship fields, although this fact is buried in the Lightning Data Service Considerations page in the documentation:
Lightning Data Service supports spanned fields with a maximum depth of five levels.
Here's a very simple example:
<aura:component implements="force:hasRecordId,flexipage:availableForRecordHome">
<aura:attribute name="targetRecord" type="Object" />
<force:recordData
recordId="{! v.recordId }"
fields="Account.Website"
targetFields="{! v.targetRecord }"
/>
<aura:if isTrue="{! not(empty(v.targetRecord.Account.Website)) }">
Account Website
</aura:if>
</aura:component>
An Apex controller will also work, but adds complexity because you'd have to write Apex, JavaScript, and Apex unit tests.
The simplest solution is a HYPERLINK() formula on the Opportunity.

JSF custom component losing input focus on ajax update

I'm writing an autocomplete custom component as a learning exercise with JSF
2.1.3. The idea (which is probably pretty familiar) is to enter some text into
and input component and present a list box with matching values. The idea is
to have a keyup javascript event on the input which calls jsf.ajax.request()
to update the component. So far I've got a component which I can include like
this:
<mycc:autocomplete id="myauto" searchMethod="#{bean.doSearch}"/>
This renders html like this:
<span id="myauto">
<input type="text" id="myauto_input" name="myauto_input"
onkeyup="com.myco.ajaxRequest(this, event)"/>
<select id="myauto_listbox" name="myauto_listbox">
<option value="1st">First</option>
<option value="2nd">Second</option>
</select>
</span>
The com.myco.ajaxRequest() javascript function (keyup) does this:
jsf.ajax.request(comp, null, {
execute: 'myauto',
render: 'myauto'
});
So because I want to rebuild and rerender the listbox with the suggestions
list, I'm re-rendering the custom component 'myauto'. By specifying execute:
'myauto' the decode() method executes and I can get the input value. By
specifying render: 'myauto' the encode...() methods execute to regenerate
the html.
This is all fine but because I'm rendering the parent of the myauto_input
component I lose input focus every time the keyup event fires.
If I specify something like render: 'myauto_listbox' (I only really want to
rerender the listbox after all) the problem is that the encode...() methods
don't execute, because they're for the custom component as a whole, not just
the listbox. And it would be in one of the encode...() methods that I rebuild
the listbox containing the suggestions.
The component extends UIInput and I generate markup in a separate renderer
(componentFamily = "javax.faces.Input") in the encodeEnd() method (so this
always runs after any supplied converter - not yet implemented). I suppose
that forcing focus from javascript is a horrible hack and to be avoided.
I'm a bit unsure where to go with this, but I suspect that what I'm seeing
indicates that I'm approaching this in the wrong way somehow. If anyone
would be good enough to point me in the right direction I'd greatly appreciate
it.
I've spent some time looking into this and the general issue of losing focus after
an ajax update is fairly common and is described in Jim Driscoll's blog (see
'Keeping Focus').
In the case of my custom component I (think I...) have to update the custom component
itself which is the parent of the input, so I'm going to lose focus as a result of the
ajax update, and that's just the way it is. As such I've looked at what needs to be
done to restore focus, and it seems that in my renderer encode I simply have to
forcibly restore focus to the input, but only when responding to the POST sent from the onkeyup event by jsf.ajax.request. I use jQuery and just calling .focus() isn't
enough because you also have to get the cursor position to the end of any existing
input. This code below seems to work ok:
<script>
jQuery(function($){var cid='#myauto_input';$(cid).focus().focus().click();$(cid).val($(cid).val());});
</script>
(note: .focus().focus().click() required for IE8, just .focus() works on chrome...)
So it looks like the horrible hack has saved the day. I did wonder if there would be
any difference if I used the jQuery ajax routines rather than the jsf ajax library but
I don't suppose it would make any difference.

Categories

Resources