Passing arguments to React component using ES6 - javascript

I am trying to create a sortable list with the react.js library "react-sortable-hoc" (https://github.com/clauderic/react-sortable-hoc).
In "SortableList" I map a function on each element of array which (should) create a "SortableElement" with the arguments key, index and value. This is how "SortableElement" is defined: https://github.com/clauderic/react-sortable-hoc/blob/master/src/SortableElement/index.js
SortableItem = SortableElement(({value,key}) =>
<Row>
<this.DragHandle/>
<ControlLabel>Question</ControlLabel>
<FormControl
componentClass="textarea"
placeholder="Enter question"
onChange={()=> {
console.log(key); //why undefined??
console.log(value);
}
}
/>
</Row>);
SortableList = SortableContainer(({items}) => {
return (
<div>
{items.map((value, index) =>
<this.SortableItem key={`item-${index}`}
index={index}
value={value}/>
)}
</div>
);
});
Unfortunately, key and index are always undefined, and I just don't understand why. If you are interested in the full code, please visit https://github.com/rcffc/react-dnd-test/blob/master/src/SortableComponent.js
Any help is appreciated.

If you look at the source for react-sortable-hoc, you'll see that when passing props in the render, index is omitted. Also, key isn't passed in props. If you change your destructuring to log props in SortableItem, you'll see an object containing just the value ('Question 1', 'Question 2', etc). If you need to access the index or key, pass them as different props.
e.g.
SortableItem = SortableElement(({value,yourIndex}) =>
<Row>
<this.DragHandle/>
<ControlLabel>Question</ControlLabel>
<FormControl
componentClass="textarea"
placeholder="Enter question"
onChange={()=> {
console.log(yourIndex);
console.log(value);
}
}
/>
</Row>
);
SortableList = SortableContainer(({items}) => {
return (
<div>
{items.map((value, index) =>
<this.SortableItem key={`item-${index}`}
index={index}
value={value}
yourIndex={index} />
)}
</div>
);
});

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>
);
}

Can't render elements from mutated Array - React

So, the problem I've faced is that when I click delete button at any index it just deletes last element
for example, if I press first delete button, it should remove first input and the delete button, but what it does is that it deletes last element only... What could be wrong?
function App() {
const [names, setNames] = React.useState([
"First",
"Second",
"third",
"fourth"
]);
const onChange= (index: number, editedName: string) => {
const mutatedNames = [...names];
mutatedNames[index] = editedName;
setNames(mutatedNames);
};
function onDelete(index: number) {
const nameArr = [...names];
nameArr.splice(index, 1);
setNames(nameArr);
}
return (
<div>
{names.map((name, index) => (
<ChildComponent
key={index}
name={name}
index={index}
onChange={onChange}
onDelete={onDelete}
/>
))}
</div>
);
}
const Child = React.memo(
({ name, index, onChange, onDelete }) => {
return (
<div>
<input
onChange={(event) => onChange(index, event.target.value)}
/>
<button onClick={() => onDelete(index)}>delete</button>
</div>
);
}
);
You are using a partially controlled input, this is almost never a good idea.
Make it fully controlled like so:
<input
value={name}
onChange={(event) => onChange(index, event.target.value)} />
I suggest you read the official guidelines about Forms and Controlled Components and the article about the uncontrolled scenario.

trying to render fields on condition based inside FieldArray react JS

I am trying to render the field based on condition that is passed to the component like as below
return (
<FieldArray name={`spaceType.mechanicalData.${mappedLibrarySourceArray}`}>
{({ fields }) => {
const dataSource = fields.map((name, index) => ({
rowKey: index,
...values.spaceType.mechanicalData[mappedLibrarySourceArray][index],
{ isProjectSystem && (select ( // getting error at this line (compile errors)
<Field
name="airSystem.isEquipmentIncluded"
component={AntdCheckboxAdapter}
type="checkbox"
label="Included"
disabled={isReadOnly}
/>
)),
},
id: (
<Field
name={name}
component={AntdSelectSectionAdapter}
isProjectSystem={isProjectSystem}
section={section}
disabled={isReadOnly}
placeholder="Select source"
render={sourceRender}
/>
),
}));
return (
<div>
<Table
columns={tableColumns}
dataSource={dataSource}
rowKey="rowKey"
/>
</div>
);
}}
</FieldArray>
);
and i am not sure where i am doing wrong with above code and isProjectSystem is boolean variable passed onto this component
I am using react JS with final form adapters plugin
Could any one please suggest any ideas on this that would be very grateful.
thanks in advance
You could do:
const dataSource = fields.map((name, index) => ({
rowKey: index,
...values.spaceType.mechanicalData[mappedLibrarySourceArray][index],
select: isProjectSystem ? (
<Field
name="airSystem.isEquipmentIncluded"
component={AntdCheckboxAdapter}
type="checkbox"
label="Included"
disabled={isReadOnly}
/>
) : null,
id: (
<Field
name={name}
component={AntdSelectSectionAdapter}
isProjectSystem={isProjectSystem}
section={section}
disabled={isReadOnly}
placeholder="Select source"
render={sourceRender}
/>
),
}));
that will have the select property there regardless. Alternately, you could change your map to conditionally add that property after.
const dataSource = fields.map((name, index) => {
const output = {
rowKey: index,
...values.spaceType.mechanicalData[mappedLibrarySourceArray][index],
id: (
<Field
name={name}
component={AntdSelectSectionAdapter}
isProjectSystem={isProjectSystem}
section={section}
disabled={isReadOnly}
placeholder="Select source"
render={sourceRender}
/>
),
};
if (isProjectSystem) {
output.select = (
<Field
name="airSystem.isEquipmentIncluded"
component={AntdCheckboxAdapter}
type="checkbox"
label="Included"
disabled={isReadOnly}
/>
);
}
return output;
});

Key is defined but it warns "Each child in a list should have a unique key prop"

although I defined a key for SearchDropDownItem it shows a warning
component DropDown
filteredItems.length > 0 ? (
filteredItems.map(item => {
return (
<SearchDropDownItem
item={item}
buttonTitle={{ buttonJoin: content.buttonJoin }}
onItemSelect={onItemSelect}
/>
);
})
) : (
<SearchDropDownItem emptyList={content.noCommunityFound} />
)
searchDropDownItem component :
const SearchDropDownItem = ({
item = { },
onItemSelect,
buttonTitle = "",
emptyList
}) => {
return (
<DropdownItem key={item.id || 1}>
{!emptyList ? (
<Box>
<Span>{item.name} </Span>
<JoinButton
item={item}
index={item.id}
onSuccess={onItemSelect}
content={buttonTitle}
/>
</Box>
) : (
<Box>
<Span>{item.emptyList}</Span>
</Box>
)}
</DropdownItem>
);
};
Warning: Each child in a list should have a unique "key" prop. Check the render method of SearchBox.
in SearchDropDownItem (at SearchBox/index.jsx:52)
You should place the key where you use the SearchDropdownItem, so in the loop.
filteredItems.length > 0 ? (
filteredItems.map(item => {
return (
<SearchDropDownItem
key={item.id} // <-- This is where it has to be
item={item}
buttonTitle={{ buttonJoin: content.buttonJoin }}
onItemSelect={onItemSelect}
/>
);
})
) : (
<SearchDropDownItem emptyList={content.noCommunityFound} />
)
Docs on keys in React: https://reactjs.org/docs/lists-and-keys.html#keys
I got the same warning message:
Warning: Each child in a list should have a unique "key" prop.
However, my problem and solution were a bit different than the accepted answer. I thought adding my solution to this question might help someone.
I am using a 3rd party component, which has a unique key. However, when I used a loop to dynamically generate several instances of the component, I got the warning message above.
The warning disappeared after I added a key prop to the component. This key is NOT part of the props for the component.
let filterJSX = [];
let i = 0;
for (let [key1, value1] of Object.entries(state.filterListNew)) {
i++;
filterJSX.push(
<MultiSelectModalField
key={i.toString()} // I added this one
items={optionList}
uniqueKey="value"
displayKey="name"
// more properties here...
/>
);
}

Sending parameter with function to child component and back to parent component

I've got a custom component called InputWithButton that looks like this:
const InputWithButton = ({ type = "text", id, label, isOptional, name, placeholder = "", value = "", showPasswordReset, error, isDisabled, buttonLabel, handleChange, handleBlur, handleClick }) => (
<StyledInput>
{label && <label htmlFor="id">{label}{isOptional && <span className="optional">optioneel</span>}</label>}
<div>
<input className={error ? 'error' : ''} type={type} id={id} name={name} value={value} placeholder={placeholder} disabled={isDisabled} onChange={handleChange} onBlur={handleBlur} autoComplete="off" autoCorrect="off" />
<Button type="button" label={buttonLabel} isDisabled={isDisabled} handleClick={() => handleClick(value)} />
</div>
{error && <Error>{Parser(error)}</Error>}
</StyledInput>
);
export default InputWithButton;
Button is another component and looks like this:
const Button = ({ type = "button", label, isLoading, isDisabled, style, handleClick }) => (
<StyledButton type={type} disabled={isDisabled} style={style} onClick={handleClick}>{label}</StyledButton>
);
export default Button;
I'm using the InputWithButton component in a parent component like this:
render() {
const { name } = this.state;
return (
<React.Fragment>
<InputWithButton label="Name" name="Name" buttonLabel="Search" value={name} handleChange={this.handleChange} handleClick={this.searchForName} />
</React.Fragment>
);
}
If the button is clicked, the searchForName function is called:
searchForName = value => {
console.log(value); //Input field value
}
This is working but I want to add another parameter to it but this time, a parameter that comes from the parent component
// handleClick={() => this.searchForName('person')}
<InputWithButton label="Name" name="Name" buttonLabel="Search" value={name} handleChange={this.handleChange} handleClick={() => this.searchForName('person')} />
The output in searchForName is now 'person' instead of the value.
I thought I could fix this with the following code:
searchForName = type => value => {
console.log(type); //Should be person
console.log(value); //Should be the value of the input field
}
However this approach doesn't execute the function anymore.
How can I fix this?
EDIT: Codepen
I would try handleClick={this.searchForName.bind(this, 'person')}, please let me know if it'll work for you.
EDIT:
I changed fragment from your codepen, it's working:
searchName(key, value) {
console.log(key);
console.log(value);
}
render() {
const { name } = this.state;
return (
<InputWithButton name="name" value={name} buttonLabel="Search" handleChange={this.handleChange} handleClick={this.searchName.bind(this, 'person')} />
)
}
as I suspected, just pass it an object and make sure you're accepting the argument in your handleClick function
handleClick={value => this.searchName({value, person: 'person'})}
or more verbose - without the syntactic sugar
handleClick={value => this.searchName({value: value, person: 'person'})}
then you can get at it with value.person
full codepen here
Hope this helps

Categories