I have a parent component that holds a string as a state. This string is composed with help from other child components.
Then the parent sends this string to a DisplayText component that displays it. However in the DisplayText component there is an internal state for that string and thus the user can change it however they like, and the result
const [myString, setMyString] = React.useState<string>('');
React.useEffect(() => {
// do some stuff with the string and save it
setMyString(string);
}, [...]);
<Textarea
value={myString}
onChange={(value) => setMyString(value)}
/>
(This is just basic React.) I would like to add a button in the parent component that forces the child to override any changes the user has made, and re-render the text coming from the parent. This happens naturally when the state in the parent changes, but how can you simulate the same effect when a button in the parent is clicked?
I could solve this by moving the internal state of editing the text from the child to the parent, so clicking the button can control that, but is there another way without doing so? Because the edited text shouldn't concern the parent. The second solution I thought of would be to force a re-render of the parent but the ways to do so are hacky (changing a dummy state).
Is there a simple solution to this?
Composing a string in multiple child components seems like a bad approach to me. But if you really need or want to do it that way, then adding a button in the partent component, that overwrites myString, should work. The props that refer to this value will update automatically. Just remove the internal state of the children, to have a 'single source of truth'.
That sounds like bad practice to me.
You should:
lift state up to parent and have a default value which is saved. Clicking the button should just reset to the default value.
If you need to change the parent state from one or more childs, you should pass down a setter function which sets the state in the parent.
Related
I've managed to add React elements dynamically depending on the content height Add React elements dynamically depending on the content height
I've prepared a codesandbox to show this:
https://codesandbox.io/s/html-react-parser-forked-8pl3b
However, the problem I'm having right know is that the child component, which shows the actual article, is not reacting to the state updated of its parent. This can be tested just by clicking on the Article 2 button.
Is it related to the usage of the reference? I can't figure out what is happening.
It's because the Article component has its own state. The html prop you pass in const [article, setArticle] = React.useState(parse(html)); is the initial value and it's ignored when the prop changes.
You can use the useEffect hook to update the state when the prop's changed. You will also need to reset the didInsertAds state:
React.useEffect(() => {
setArticle(parse(html));
setDidInsertAds(false);
}, [html]);
I am facing a weird issue that DOM gets re-render in case of any input key pressed in input field. I am using FormControl. sibling component to the input field on DOM has OnPush
strategy.
when i enter anything or click in the input field my DOM get re-render, input field value has no effect on the sibling component so its #Input properties remain same( Strategy of this component is onPush) but it re-render causing no call of lifecycle method like ngOnInit , ngOnChanges.
because of this unpredicted component re-rendering causing distorting of component UI because no lifecycle get call like ngOnInit ngOnChanges so no initialisation function call of that component.
so component get render with previous values can anyone tell me why this is happen.
is this because of FormControl i am using or something else.
There is an UI I have created using React. There are two text fields to enter value, after entering and saving those values will be populated in a table below the two fields(we are using antd for designing).
However when I click a single record in the table and click edit in that particular record data from that record will be populated to the above mentioned text fields. When this happens I want my app to scroll up and show those two text fields which are ready to be edited.
But currently it stays at the same position after clicked edit, without scrolling up and showing two text fields. Here's an image descripting my experience
Check this answer to find how to control srollTop: https://stackoverflow.com/a/55184755/2360631
But I don't think it's a good idea, maybe you can consider to freeze the edit area otherwise when you finish edit you may need to scroll back again...
Basically you want to set focus to some component after a re-render.
To refer to a particular component, use react refs
make a react ref of whatever you want to set focus to and assign it as a ref prop
constructor() {
super();
this.foo = React.createRef();
}
componentDidUpdate() {
this.foo.current.focus();
}
<Bar ref={this.foo}> .... </Bar>
foo is the name of ref
Bar is the component you want to set focus to
in your case it can be a parent of both input fields or any one of the input fields
All the examples I have found that keep local state can't provide an initial value for the input. In my case a parent component retrieves field from a server and passes these to my input form where the fields shall be editable. But I don't want to pass each change back up the hierarchy if I can avoid it, rather only when the form is submitted (either via button or by pressing enter)
Update: the usage is as follows. Imagine a todo list. The top level holds the list and the detail component. When I click at the list the detail should update to show the selected todo text. That text should be editable.
So as far the the detail component goes the initial state of the input is the text from the list that gets passed down in props. It needs to change when a different todo in the list is selected. On the other hand I should be able to edit it and when submit triggered that todo text should be passed back up via a callback prop.
So I have to keep local state to collect the input, but I want that state to be initialized with the existing todo text from the list. If I use the Facebook example of an uncontrolled form, I find the edited text remains displayed when I switch to a different todo in the list. Maybe I'm doing it wrong or is it a conceptual problem? Using controlled input initializing the state in the constructor doesn't work either because the constructor only gets called once (not on each re-render)!
I solved the problem by using the lifecycle method componentWillReceiveProps(nextprops) where I can set the state to the new props. This method gets called each time a re-render becomes necessary - in my case because the parent changes the childs props.
See https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
You can set the initial state based on the property passed in from the parent, then edit that state in the component before submitting with the form submission
Hi I want to hide an adf component automatically.I have a selectOneChoice that contain some number (from 1 to 12).
Example when I select 2, it show's two field automatically without clicking any button..
i used this function to hide a declared componenet but just when i click a button..
function enableField(actionEvent) {
var nameInputText = actionEvent.getSource().findComponent("soc1");
nameInputText.setProperty("visible", true);
actionEvent.cancel();
}
i set the componement "soc1" visible = true than through the javascript function i change it..
SO the probleme here is how to read the number from the selectonechoise and how to set the component visible directly without clicking any button.
Actually Rendered won't do what you want. You want to use Visible property instead. Rendered causes the actual markup for the component not to be rendered on the page, so a Partial Refresh will not cause it to appear. Rendered is reserved, usually, to hide items that are secure. We set rendered property to false on the item(s), but then refresh the parent containing component - usually a layout manager - then it works. So either refresh the layout manager that contains the item or use Visible. I demonstrated this exact use case last week in class and it works as described.
Basicaly, you don't need javascript solution or any programming to achieve this.
You should set attributes rendered(this way component won't be rendered at the page at all) and partialTriggers that points to selectOneChoice component for components you want to show or hide. Also you have to set autoSubmit="true" for your selectOneChoice component.
<af:selectOneChoice id="soc1" autoSubmit="true" .../>
<af:panelGroupLayout id="plg1" partialTriggers="soc1">
<af:outputText id="ot1" rendered="#{bindings.lov.inputValue le 1}" inputValue="text1"/>
</af:panelGroupLayout>
Note: its not working code, just a sample
It will work following way, on valueChange event at selectOneChoice component value is submitted and partialRefresh fires for components that have it in partialTriggers specified. And rendered attribute will either render or remove component depending on it's EL expression. Components that should be managed wrapped into another component to make sure PPR reach it when they ain't rendered.