How can I accessing nested component in react from parent component? - javascript

I want to access a nested component from parent component.
This is Bill Form.jsx
import BillDetailForm from './BillDetailForm';
render(){
return (
<form onSubmit={handleSubmit}>
<FieldArray
name= 'detail'
component={BillDetailForm}
placeholder= '...detail'
label='Detail'
/>
</form>
);
}
}
BillForm is the parent component.
This is a nested component or child component of BillForm: BillDetailForm.jsx
render(){
return(
<form onSubmit={ handleSubmit }>
<div>Detail:</div>
<FieldArray
name= 'detail'
component={RenderDetail}
label='Detail'
/>
</form>
)
}
Inside BillDetailForm is RenderDetail:
const RenderDetail = ({fields, meta: { error,submitFailed}},props) => (
<dl>
<dt>
<button type="button" className= 'btn btn-primary' onClick={() => fields.push()}>Add
Detail</button>
{submitFailed && error && <span>{error}</span>}
</dt>
{ fields.map((registerDetail, index) =>
//In the following line renderDetail is accesing Detail component.
<Detail detailItem={registerDetail} fields={fields} index={index} key={index}/>
)
}
{error && <dt className="error">{error}</dt>}
</dl>
);
This is Detail Class Component:
class Detail extends Component{
render(){
const{detailItem,index,fields,isSubtotal} = this.props;
return(
<dd key={index}>
<br></br>
<button className= 'btn btn-light mr-2'
type="button"
title="Remove detail"
onClick={() => { fields.remove(index)
if(fields.length == 0 || fields.length === undefined){
}
try{
for(let x in fields){
fields.remove(index)
let d = fields.selectedIndex;
if(fields.remove(index) && d >= 1 && d< fields.length ){
fields.removeAll(index);
}
}
}catch{console.info("deletes non numerical index")}
}}> Delete </button>
<h4>DetailRegister #{index + 1}</h4>
<Field
id={`${detailItem}._id`}
name={`${detailItem}.quantity`}
component= {NumberPickerInteger}
placeholder= '...quantity'
label = "Quantity"
/>
<br></br>
<h3><b>Product</b></h3>
<Field
id={`${detailItem}._id`}
name={`${detailItem}.product.code`}
type="number"
component= {RenderFieldNumeric}
placeholder='...Product's code'
label = "Product's code"
/>
<Field
id={`${detailItem}._id`}
name={`${detailItem}.product.name`}
type="text"
component= {RenderField}
placeholder='...Product's name'
label = "Product's name"
/>
<Field
id={`${detailItem}._id`}
name={`${detailItem}.product.price`}
component= {NumberPickerr}
placeholder= '...Price'
label = "Product's price"
/>
<br></br>
<h3><b>Subtotal</b></h3>
<Field
id={`${detailItem}._id`}
name={`${detailItem}.subtotal`}
component= {SubtotalWidget}
placeholder= '...subtotal'
label = "Subtotal"
>
{isSubtotal}
</Field>
</dd>
);
}
}
I want to access e.g ${props.detailItem}.subtotal that is in Detail from BillForm. BillForm accesses to BillDetailForm, BillDetailForm accesses to renderDetail, and last renderDetail acceses to Detail.
The question is: How can I access and use props like quantity and subtotal with dynamic index (props.index) from BillForm? I want to access Detail component from BillForm, respecting the following secuence in order access: BillForm -> BillDetailForm -> RenderDetail -> Detail

If I understand correctly what you are saying, it seems you are going against the ethos of React. If your parent component wants access to a piece of data, then that data should start in the parent and be passed down. This way, if the data changes it will call a re-render of components and update all necessary components.
Some other advice. Try not o have so much logic inside your component handlers, it looks messy and will run every render cycle. Abstract this into a method on the class and call it when required.
My example will hopefully help you with your issue, but I recommend having a read of the React documentation as it is very good with simple examples.
The use of class will be deprecated eventually in favour of function components and the Hooks API.
class ParentComponent {
state = {
value: 0,
}
methodToDoSomething = (passedVal) => {
this.setState({
value: passVal,
});
}
render() {
const myState = this.state;
return (
<Component {...myState} />
)
}
}
class Component {
state = {}
render() {
const { value , methodToDoSomething } = this.props;
return (
<div onClick={methodToDoSomething}>
{value}
</div>
)
}
}
// Hooks API
const ParentComponent = () => {
const [stateVal, updateState] = React.useState('myString');
return (
<div>
{stateVal}
<Component passedVal={stateVal} passedHandler={updateState} />
</div>
)
}
const Component = ({ stateVal, passedHandler }) => {
function updateMyValue() {
passedHandler('menewvalue');
}
return (
<div onClick={updateMyValue}>
{stateValue}
<div/>
)
}
To avoid passing lots down all the children components, I would recommend reading up on the Context Hook.
*** UPDATE ***
The above example is rudimentary and tries to answer the question presented, there are always many ways to solve a problem.
Passing props can be messy and a maintenance overhead. Most larger applications will benefit from using a state library to manage their global state. The Context API is a good tool to use to wrap a cohesive set of components so they can share data/props without prop-drilling (passing props down many child components).
Custom hooks are another good way to share data. Create a hook containing your data and any other methods for the task and use this hook inside parent and child components to share said data.

Related

Reactjs: How to access state of child component.from a method in parent component that depends on state of child component

I need to access a method handleCancelEdit() defined in parent component. But, the matter here is that every child component will have its own cancelEdit state. Now, what is happening is, if I call handleCancelEdit() from one child component, every other of the same child components is taking the state and updating themselves(the method is not completely defined yet). That's why, I have defined the cancelEdit state in the child component, thinking that it belongs to this child component only.
Now, how do I make the handleCancelEdit() method make changes to the only child component which called it?
The parent:
function Parent() {
const handleCancelEdit = () => {
setCancelEdit(!cancelEdit); // defined in child component
setEdit(!edit); // defined in child component
...
};
return (
<div>
<ChildComponent
fieldName={"Email"}
value={email}
inputType={"text"}
placeHolder={"Enter email"}
name={"email"}
on_change={(e)=>setEmail(e.target.value)}
on_click={handleUserEmail}
/>
<ChildComponent
fieldName={"About"}
value={about}
inputType={"text"}
placeHolder={"Enter some details about yourself"}
name={"about"}
on_change={(e)=>setAbout(e.target.value)}
on_click={handleUserAbout}
/>
</div>
);
}
Child component:
function ChildComponent({fieldName, value, inputType, placeHolder, name, on_change, on_click}) {
const [ edit, setEdit ] = useState(false);
const [ cancelEdit, setCancelEdit ] = useState(false)
const isEdit = edit;
return (
<p>{fieldName}: {value === ''? (
<span>
<input type={inputType} placeholder={placeHolder}
name={name} onChange={on_change}
/>
<button type="submit" onClick={on_click}>Add</button>
</span>
) : ( !isEdit ? (<span> {value} <button onClick={e=>setEdit(!edit)}>Edit</button></span>) :
(<span>
<input type={inputType} value={value}
name={name} onChange={on_change}
/>
<button type="submit" onClick={on_click}>Save</button>
<button type="submit" onClick={handleCancelEdit}>Cancel</button>
</span>)
)}
</p>
);
};
I hope it could make it understandable that one child component should not make others to update. Now, how do I do it in this scenario?
EDIT
After making changes according to Linda Paiste:
The input field in the child component is not working even though the onChange in both parent and child is correct!
It is always more logical to pass state and data down rather than up. If the Parent needs to interact with the edit state then that state should live in the parent. Of course we want independent edit states for each child, so the parent can't just have one boolean. It needs a boolean for each child. I recommend an object keyed by the name property of the field.
In ChildComponent, we move isEdit and setEdit to props. handleCancelEdit is just () => setEdit(false) (does it also need to clear the state set by onChange?).
function ChildComponent({fieldName, value, inputType, placeHolder, name, onChange, onSubmit, isEdit, setEdit}) {
return (
<p>{fieldName}: {value === ''? (
<span>
<input type={inputType} placeholder={placeHolder}
name={name} onChange={onChange}
/>
<button type="submit" onClick={onSubmit}>Add</button>
</span>
) : ( !isEdit ? (<span> {value} <button onClick={() =>setEdit(true)}>Edit</button></span>) :
(<span>
<input type={inputType} value={value}
name={name} onChange={onChange}
/>
<button type="submit" onClick={onSubmit}>Save</button>
<button type="submit" onClick={() => setEdit(false)}>Cancel</button>
</span>)
)}
</p>
);
};
In Parent, we need to store those isEdit states and also create a setEdit function for each field.
function Parent() {
const [isEditFields, setIsEditFields] = useState({});
const handleSetEdit = (name, isEdit) => {
setIsEditFields((prev) => ({
...prev,
[name]: isEdit
}));
};
/* ... */
return (
<div>
<ChildComponent
fieldName={"Email"}
value={email}
inputType={"text"}
placeHolder={"Enter email"}
name={"email"}
onChange={(e) => setEmail(e.target.value)}
onSubmit={handleUserEmail}
isEdit={isEditFields.email}
setEdit={(isEdit) => handleSetEdit("email", isEdit)}
/>
<ChildComponent
fieldName={"About"}
value={about}
inputType={"text"}
placeHolder={"Enter some details about yourself"}
name={"about"}
onChange={(e) => setAbout(e.target.value)}
onSubmit={handleUserAbout}
isEdit={isEditFields.about}
setEdit={(isEdit) => handleSetEdit("about", isEdit)}
/>
</div>
);
}
You can clean up a lot of repeated code by storing the values as a single state rather than individual useState hooks. Now 5 of the props can be generated automatically just from the name.
function Parent() {
const [isEditFields, setIsEditFields] = useState({});
const [values, setValues] = useState({
about: '',
email: ''
});
const getProps = (name) => ({
name,
value: values[name],
onChange: (e) => setValues(prev => ({
...prev,
[name]: e.target.value
})),
isEdit: isEditFields[name],
setEdit: (isEdit) => setIsEditFields(prev => ({
...prev,
[name]: isEdit
}))
});
const handleUserEmail = console.log // placeholder
const handleUserAbout = console.log // placeholder
return (
<div>
<ChildComponent
fieldName={"Email"}
inputType={"text"}
placeHolder={"Enter email"}
onSubmit={handleUserEmail}
{...getProps("email")}
/>
<ChildComponent
fieldName={"About"}
inputType={"text"}
placeHolder={"Enter some details about yourself"}
onSubmit={handleUserAbout}
{...getProps("about")}
/>
</div>
);
}

How can I test functions as child in React? The snapshot is

I was creating a component that returns a label and a children, this child is a function that evaluates if the field has type 'input' or 'textarea' and returns it:
export const Field = ({
fieldType,
}) => {
return (
<>
<label htmlFor={name}> {label}</label>
{() => {
switch (fieldType) {
case 'textarea':
return (
<textarea
/>
);
default:
return (
<input/>
);
}
}}
</>
);
};
I like to start my test by creating a snapshot of the component
describe('Unit testing: <Field /> component', () => {
test('Should render correctly ', () => {
const wrapper = shallow(<Field fieldType='textarea' />);
expect(wrapper).toMatchSnapshot();
});
});
This is the result of my snapshot (I'm using enzyme-to-json):
exports[`Unit testing for Field component Should render correctly 1`] = `
<Fragment>
<label
htmlFor="testField"
>
Test Label
</label>
<Component />
</Fragment>
`;
As you can see, the child has been rendered just as and this is very fuzzy to me... I would like to know how can I exactly test that my component is really rendering either an input or a textarea...
I've found a possible solution that actually it's good for me:
const innerWrapper = shallow(wrapper.prop('children')[1]());
This innerWrapper creates a shallow render from the children.
The snapshot shows what I wanted:
exports[`Unit testing for Field component Function as children should render correctly 1`] = `
<textarea
autoComplete="off"
id="testField"
name="testField"
value=""
/>
`;
The complete test that I've implemented:
test('Function as children should render correctly', () => {
const innerWrapper = shallow(wrapper.prop('children')[1]());
expect(innerWrapper).toMatchSnapshot();
expect(innerWrapper.find(props.fieldType).exists()).toBe(true);
});
And yes, I've ran the test and it passed.
You mentioned in your answer to your question :
I've found a possible solution that actually it's good for me:
But it's a wrong solution. You have a wrong component, and you changed your test to ignore it. your component is like:
export const Field = ({fieldType,}) => {
return (
<>
<label htmlFor={name}> {label}</label>
{() => {return <input />}} <---- it's just a component defination.
</>
);
};
And if you use it like:
<Field />
It will only render label, not the textarea nor the input. (Because a function inside the render function is considered as a component definition, you should call it in order to get an element from it to render.)
So the test was correct, but your component is wrong. Change your component to:
export const Field = ({fieldType,}) => {
const input = () => {
return <input />
}
return (
<>
<label htmlFor={name}> {label}</label>
{input()}
</>
);
};
To render the input component, not just defining it.

Cannot update during an existing state transition in stateless component

I have the following warning :
Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor).
with React-redux-router that I understand, but do not know how to fix.
This is the component that is generating the warning.
const Lobby = props => {
console.log("props", props)
if (!props.currentGame)
return (
<div>
<input type="text" ref={input => (roomName = input)} />
<button
className="button"
onClick={() => {
props.createRoom(roomName.value)
}}
>
Create a room
</button>
</div>
)
else
return (
<div>
{props.history.push(`/${props.currentGame}[${props.username}]`)}
</div>
)
}
export default Lobby
What I'm doing here is that my component receives the currentGame property from the Redux store. This property is initialized as null.
When the user creates a game, I want to redirect him on a new URL generated by the server that I assign inside the property currentGame with a socket.io action event that is already listening when the container of the component Lobby is initialized.
However, since the currentGame property changes, the component is re-rendered, and therefore the line
{props.history.push(`/${props.currentGame}[${props.username}]`)}
generates a warning since the property currentGame now has a value, and the history property should not get modified during the re-render.
Any idea on how to fix it ?
Thanks!
You should not write props.history.push in render, instead use Redirect
const Lobby = props => {
console.log("props", props)
if (!props.currentGame)
return (
<div>
<input type="text" ref={input => (roomName = input)} />
<button
className="button"
onClick={() => {
props.createRoom(roomName.value)
}}
>
Create a room
</button>
</div>
)
else
return (
<div>
<Redirect to={`/${props.currentGame}[${props.username}]`} />
</div>
)
}
Do one thing, instead of writing the condition and pushing with history.push(), just put the code inside componentDidMount() if you are trying to do in the beginning.
componentDidMount(){
if(condition){
history.push('/my-url');
}
}

Can't delete the item I am clicking the delete button for - React [duplicate]

Lets say I have a view component that has a conditional render:
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
MyInput looks something like this:
class MyInput extends React.Component {
...
render(){
return (
<div>
<input name={this.props.name}
ref="input"
type="text"
value={this.props.value || null}
onBlur={this.handleBlur.bind(this)}
onChange={this.handleTyping.bind(this)} />
</div>
);
}
}
Lets say employed is true. Whenever I switch it to false and the other view renders, only unemployment-duration is re-initialized. Also unemployment-reason gets prefilled with the value from job-title (if a value was given before the condition changed).
If I change the markup in the second rendering routine to something like this:
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
It seems like everything works fine. Looks like React just fails to diff 'job-title' and 'unemployment-reason'.
Please tell me what I'm doing wrong...
Change the key of the component.
<Component key="1" />
<Component key="2" />
Component will be unmounted and a new instance of Component will be mounted since the key has changed.
Documented on You Probably Don't Need Derived State:
When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.
What's probably happening is that React thinks that only one MyInput (unemployment-duration) is added between the renders. As such, the job-title never gets replaced with the unemployment-reason, which is also why the predefined values are swapped.
When React does the diff, it will determine which components are new and which are old based on their key property. If no such key is provided in the code, it will generate its own.
The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div and I believe that would trigger a re-render of all children (which is why it works). Had you added the span to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).
Here's what the official React documentation says:
The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.
When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
You should be able to fix this by providing a unique key element yourself to either the parent div or to all MyInput elements.
For example:
render(){
if (this.state.employed) {
return (
<div key="employed">
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div key="notEmployed">
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
OR
render(){
if (this.state.employed) {
return (
<div>
<MyInput key="title" ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
<MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
Now, when React does the diff, it will see that the divs are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title and unemployment-reason since they now have different keys.
You can of course use any keys you want, as long as they are unique.
Update August 2017
For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.
Update November 2017
This update should've been posted a while ago, but using string literals in ref is now deprecated. For example ref="job-title" should now instead be ref={(el) => this.jobTitleRef = el} (for example). See my answer to Deprecation warning using this.refs for more info.
Use setState in your view to change employed property of state. This is example of React render engine.
someFunctionWhichChangeParamEmployed(isEmployed) {
this.setState({
employed: isEmployed
});
}
getInitialState() {
return {
employed: true
}
},
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.
import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';
const LifeActionCreate = () => {
let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();
const onCreate = e => {
const db = firebase.firestore();
db.collection('actions').add({
label: newLifeActionLabel
});
alert('New Life Insurance Added');
setNewLifeActionLabel('');
};
return (
<Card style={{ padding: '15px' }}>
<form onSubmit={onCreate}>
<label>Name</label>
<input
value={newLifeActionLabel}
onChange={e => {
setNewLifeActionLabel(e.target.value);
}}
placeholder={'Name'}
/>
<Button onClick={onCreate}>Create</Button>
</form>
</Card>
);
};
Some React Hooks in there

Access the model from the Edit component

I have the following edit component
const UserEdit = (props) => (
<Edit {...props}>
<TabbedForm >
<FormTab label="User Account">
<DisabledInput source="id" />
<TextInput source="email" />
<TextInput source="password" type="password"/>
<TextInput source="name" />
<TextInput source="phone" />
<SelectInput source="role" optionValue="id" choices={choices} />
</FormTab>
<FormTab label="Customer Information">
<BooleanInput label="New user" source="Customer.is_new" />
<BooleanInput label="Grandfathered user" source="Customer.grandfathered" />
</FormTab>
</TabbedForm >
</Edit>
);
The second FormTab (Customer Information) I only need it to appear if the User model has some information associated (the JSON is something like):
{
id: <int>,
name: <string>,
....
Customer: {
is_new: true,
grandfathered: true,
}
}
I'd like to know if I can access somehow the model information (in this case, if the Customer key exists and has info) in order to be able to render or not the <FormTab label="Customer Information">
I'm a little bit lost with the global redux state. I know the data is in the state because I've debugged it with the Redux tools. (I tried to look in this.props but I couldn't find anything to access the global state)
Thanks.
If you need the object when you are building the form you could connect it to the redux store.
import { connect } from 'react-redux';
// this is just a form, note this is not being exported
const UserEditForm = (props) => {
console.log(props.data); // your object will be in props.data.<id>
let customFormTab;
const id = props.params.id;
if (typeof props.data === 'object' && && props.data.hasOwnProperty(id)) {
if (props.data[id].something) {
customFormTab = <FormTab>...;
}
}
return <Edit {...props}>
<Formtab...
{customFormTab}
</Edit>;
}
// this is your exported component
export const UserEdit = connect((state) => ({
data: state.admin.User.data
}))(UserEditForm);
PS: I'm not sure if this is a nice or desired solution (hopefully someone will correct me if I'm doing something not according to how redux or admin-on-rest was designed).

Categories