I have a Fields component that I am trying to use sometimes by itself and sometimes from inside a FieldArray component. I have added a snippet below with a simplified model.
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { reduxForm, Fields, FieldArray, reducer as formReducer } from 'redux-form';
const reducers = {
form: formReducer
};
const reducer = combineReducers(reducers);
const store = createStore(reducer);
const renderSharedComponent = (fields) => {
console.log(fields);
return (<div>Shared Component</div>);
};
const renderHashes = ({ fields }) => (
<div>
{
fields.map((field) => (
<Fields
key={ field }
names={ [`${field}.value`, `${field}.valueIsRegex`] }
component={ renderSharedComponent }
/>
))
}
</div>
);
const ReactComponent = () => (
<div>
<FieldArray
name="hashes"
component={ renderHashes }
/>
<Fields
names={ ['value', 'valueIsRegex'] }
component={ renderSharedComponent }
/>
</div>
);
const ReduxForm = reduxForm({
form: 'default',
initialValues: {
hashes: [{}]
}
})(ReactComponent);
ReactDOM.render((
<div>
<Provider store={ store }>
<ReduxForm />
</Provider>
</div>
), document.getElementById('content'));
When I use the Fields component by itself, the fields argument from inside renderSharedComponent has the following form:
{
value: { input: {...}, meta: {...} },
valueIsRegex: { input: {...}, meta: {...} },
names: [ 'value' , 'valueIsRegex' ]
}
When I use the Fields component inside a FieldArray component, the fields argument from inside renderSharedComponent has the following form:
{
hashes: [
{
value: { input: {...}, meta: {...} },
valueIsRegex: { input: {...}, meta: {...} }
}
],
names: [ 'hashes[0].value' , 'hashes[0].valueIsRegex' ]
}
If I will be using the Fields component inside a FieldArray component with a different name (let's say paths) the names property will change accordingly (eg. names: [ 'paths[0].value' , 'paths[0].valueIsRegex' ]).
I am trying to get the value and valueIsRegex objects in a generic way that will support any of the cases I presented above.
Right now I have created a function where I use a RegEx to determine the fields. But I was wondering if anyone knows a better way to do this (maybe there is a Redux Form util that maybe I missed when reading the documentation).