material-ui Items are not showing. I want to show categories of products in SelectField but its not working.
whwn I click on selectfield it does not show any item
All code of my component is given below
import React, { Component } from 'react'
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
const style = {
padding: '10px',
textAlign: 'center'
};
const categories = ["mobile","laptop","camera"];
class AddProduct extends Component {
constructor(props) {
super();
this.state = {
productName: '',
productCategory: '',
}
this.submit = this.submit.bind(this);
this.inputHandler = this.inputHandler.bind(this);
}
inputHandler(e) {
this.setState({
[e.target.name]: e.target.value
})
}
handleChangeCategory = (event, index, value) => {this.setState({productCategory:value}); console.log("value", value)}
render() {
return (
<div ><center>
<h1>Add Product for Auction</h1>
<form onSubmit={this.submit} >
<br />
<br />
<SelectField
floatingLabelText="Catogory"
value={this.state.productCategory}
onChange={this.handleChangeCategory}
>
<MenuItem value={"mobile"} primaryText="Mobile" />
<MenuItem value={"laptop"} primaryText="Laptop" />
<MenuItem value={"camera"} primaryText="Camera" />
</SelectField><br />
<br />
<TextField
type="text"
hintText="Product Title"
name="productName"
value={this.state.productName}
floatingLabelText="Product Title"
onChange={this.inputHandler}
/>
<RaisedButton type="submit" label="Add Product" primary={false} secondary={true} /> <br /><br />
</form>
</center>
</div>
);
}
}
export default AddProduct;
You haven't defined the function submit and according to your code you are trying to bind it.
this.submit = this.submit.bind(this);
define the function submit
submit(){
// do something
}
And try to use ES6 fat arrow functions so you dont have to bind each and every function, like you have done in the above code.
Try something like this (using ES6 fat arrows)
import React, { Component } from 'react'
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
const style = {
padding: '10px',
textAlign: 'center'
};
const categories = ["mobile","laptop","camera"];
class AddProduct extends Component {
constructor(props) {
super();
this.state = {
productName: '',
productCategory: '',
}
}
submit =()=>{
}
inputHandler =(e)=> {
this.setState({
[e.target.name]: e.target.value
})
}
handleChangeCategory = (event, index, value) => {this.setState({productCategory:value}); console.log("value", value)}
render() {
return (
<div ><center>
<h1>Add Product for Auction</h1>
<form onSubmit={this.submit} >
<br />
<br />
<SelectField
floatingLabelText="Catogory"
value={this.state.productCategory}
onChange={this.handleChangeCategory}
>
<MenuItem value={"mobile"} primaryText="Mobile" />
<MenuItem value={"laptop"} primaryText="Laptop" />
<MenuItem value={"camera"} primaryText="Camera" />
</SelectField><br />
<br />
<TextField
type="text"
hintText="Product Title"
name="productName"
value={this.state.productName}
floatingLabelText="Product Title"
onChange={this.inputHandler}
/>
<RaisedButton type="submit" label="Add Product" primary={false} secondary={true} /> <br /><br />
</form>
</center>
</div>
);
}
}
export default AddProduct;
Related
I am using react hook forms to create forms in my application:
import "./styles.css";
import { useForm } from "react-hook-form";
export default function App() {
const { register, setFocus, handleSubmit } = useForm({
defaultValues: { inputText: "", inputCheckbox: false }
});
const onSubmit = (data) => {
console.log(data);
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)} className="form">
<br />
<label>inputCheckbox</label>
<input type="checkbox" {...register("inputCheckbox")} />
<br />
<br />
<label>inputCheckbox2</label>
<input type="checkbox" {...register("inputCheckbox")} />
<button
onClick={() => {
setFocus("inputCheckbox");
}}
>
setFocus inputCheckbox
</button>
<br />
<br />
<button type="submit">Submit</button>
</form>
</div>
);
}
I try to set focus when i click on the button, but it does not work, why and how to fix using the library API?
demo: https://codesandbox.io/s/icy-feather-eh1crv?file=/src/App.js:0-899
My App Component is here
import React, { useEffect } from 'react';
import './App.css';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './components/auth/Login';
import Register from './components/auth/Register';
import { Provider } from 'react-redux';
import store from './store';
import Alert from './components/layout/Alert';
import setAuthToken from './utils/setAuthToken';
import { loadUser } from './actions/auth';
import Dashboard from './components/dashboard/Dashboard';
import PrivateRoute from './components/routing/PrivateRoute';
import CreateProfile from './components/profile-form/CreateProfile';
import EditProfile from './components/profile-form/EditProfile';
import AddExperience from './components/profile-form/AddExperience';
import AddEducation from './components/profile-form/AddEducation';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<>
<Navbar />
<Route exact path='/' component={Landing} />
<section className='container'>
<Alert />
<Switch>
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<PrivateRoute exact path='/dashboard' component={Dashboard} />
<PrivateRoute
exact
path='/create-profile'
component={CreateProfile}
/>
<PrivateRoute
exact
path='/edit-profile'
component={EditProfile}
/>
<PrivateRoute
exact
to='/add-experience'
component={AddExperience}
/>
<PrivateRoute
exact
path='/add-education'
component={AddEducation}
/>
</Switch>
</section>
</>
</Router>
</Provider>
);
};
export default App;
My AddExperience Component is here
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { addExperience } from '../../actions/profile';
import { Link, withRouter } from 'react-router-dom';
const AddExperience = ({ addExperience, history }) => {
const [formData, setFormData] = useState({
company: '',
title: '',
location: '',
from: '',
to: '',
current: false,
description: '',
});
const [toDateDisabled, toggleDisabled] = useState(false);
const { company, title, location, from, to, current, description } = formData;
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
return (
<>
<h1 className='large text-primary'>Add An Experience</h1>
<p className='lead'>
<i className='fas fa-code-branch'></i> Add any developer/programming
positions that you have had in the past
</p>
<small>* = required field</small>
<form
className='form'
onSubmit={(e) => {
e.preventDefault();
addExperience(formData, history);
}}
>
<div className='form-group'>
<input
type='text'
placeholder='* Job Title'
name='title'
value={title}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className='form-group'>
<input
type='text'
placeholder='* Company'
name='company'
value={company}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className='form-group'>
<input
type='text'
placeholder='Location'
name='location'
value={location}
onChange={(e) => onChange(e)}
/>
</div>
<div className='form-group'>
<h4>From Date</h4>
<input
type='date'
name='from'
value={from}
onChange={(e) => onChange(e)}
/>
</div>
<div className='form-group'>
<p>
<input
type='checkbox'
name='current'
checked={current}
value={current}
onChange={(e) => {
setFormData({ ...formData, current: !current });
toggleDisabled(!toDateDisabled);
}}
/>{' '}
Current Job
</p>
</div>
<div className='form-group'>
<h4>To Date</h4>
<input
type='date'
name='to'
value={to}
onChange={(e) => onChange(e)}
disabled={toDateDisabled ? 'disable' : ''}
/>
</div>
<div className='form-group'>
<textarea
name='description'
cols='30'
rows='5'
placeholder='Job Description'
value={description}
onChange={(e) => onChange(e)}
></textarea>
</div>
<input type='submit' className='btn btn-primary my-1' />
<a className='btn btn-light my-1' href='dashboard.html'>
Go Back
</a>
</form>
</>
);
};
AddExperience.propTypes = {
addExperience: PropTypes.func.isRequired,
};
export default connect(null, { addExperience })(AddExperience);
Here is my AddEducation Component
import React, { useState, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { addEducation } from '../../actions/profile';
import { Link, withRouter } from 'react-router-dom';
const AddEducation = ({ addEducation, history }) => {
const [formData, setFormData] = useState({
school: '',
degree: '',
fieldofstudy: '',
from: '',
to: '',
current: false,
description: '',
});
const [toDateDisabled, toggleDisabled] = useState(false);
const {
school,
degree,
fieldofstudy,
from,
to,
current,
description,
} = formData;
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
return (
<Fragment>
<h1 className='large text-primary'>Add Your Education</h1>
<p className='lead'>
<i className='fas fa-code-branch'></i> Add any School or bootcamp that
you have attended
</p>
<small>* = required field</small>
<form
className='form'
onSubmit={(e) => {
e.preventDefault();
addEducation(formData, history);
}}
>
<div className='form-group'>
<input
type='text'
placeholder='* School or Bootcamp'
name='school'
value={school}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className='form-group'>
<input
type='text'
placeholder='* Degree or Certificate'
name='degree'
value={degree}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className='form-group'>
<input
type='text'
placeholder='fieldofstudy'
name='fieldofstudy'
value={fieldofstudy}
onChange={(e) => onChange(e)}
/>
</div>
<div className='form-group'>
<h4>From Date</h4>
<input
type='date'
name='from'
value={from}
onChange={(e) => onChange(e)}
/>
</div>
<div className='form-group'>
<p>
<input
type='checkbox'
name='current'
checked={current}
value={current}
onChange={(e) => {
setFormData({ ...formData, current: !current });
toggleDisabled(!toDateDisabled);
}}
/>{' '}
Current Job
</p>
</div>
<div className='form-group'>
<h4>To Date</h4>
<input
type='date'
name='to'
value={to}
onChange={(e) => onChange(e)}
disabled={toDateDisabled ? 'disable' : ''}
/>
</div>
<div className='form-group'>
<textarea
name='description'
cols='30'
rows='5'
placeholder='Programme Description'
value={description}
onChange={(e) => onChange(e)}
></textarea>
</div>
<input type='submit' className='btn btn-primary my-1' />
<a className='btn btn-light my-1' href='dashboard.html'>
Go Back
</a>
</form>
</Fragment>
);
};
AddEducation.propTypes = {
addEducation: PropTypes.func.isRequired,
};
export default connect(null, { addEducation })(AddEducation);
And Lastly here is the DashboardActions Component
import React from 'react';
import { Link } from 'react-router-dom';
const DashboardActions = () => {
return (
<div className='dash-buttons'>
<Link to='/edit-profile' className='btn btn-light'>
<i className='fas fa-user-circle text-primary' /> Edit Profile
</Link>
<Link to='/add-experience' className='btn btn-light'>
<i className='fab fa-black-tie text-primary' /> Add Experience
</Link>
<Link to='/add-education' className='btn btn-light'>
<i className='fas fa-graduation-cap text-primary' /> Add Education
</Link>
</div>
);
};
export default DashboardActions;
The Problem is When i Click on AddExperience it opens correctly with correct url but when i click on AddEducation it Opens the same Add Experience Form but url changed Correctly.
There is a typo here:
<PrivateRoute
exact
to='/add-experience'
component={AddExperience}
/>
The 'to' should be replaced with 'path'
I am trying to create a filter for my list of doctors, but it is not working.
I tried to follow some tutorials and it didn't work.
Where can I be wrong?
Follow my repository with the complete project, but my problem is in the index.js file (src / components / Doctors): Frontend Repository
I appreciate the help, because I've been trying to create a filter for more than 1 week and I can't.
Below, complete code from index.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import DoctorsActions from '~/store/ducks/doctors';
import MembersActions from '~/store/ducks/members';
import Can from '~/components/Can';
import Modal from '../Modal';
import Members from '~/components/Members';
import Button from '../../styles/components/Button';
import {
Editbutton,
Cancelbutton,
Savebutton,
Container,
Doctor,
MenuItem,
SearchField,
} from './styles';
class Doctors extends Component {
static propTypes = {
getDoctorsRequest: PropTypes.func.isRequired,
openDoctorModal: PropTypes.func.isRequired,
closeDoctorModal: PropTypes.func.isRequired,
createDoctorRequest: PropTypes.func.isRequired,
openMembersModal: PropTypes.func.isRequired,
activeTeam: PropTypes.shape({
name: PropTypes.string,
}),
doctors: PropTypes.shape({
data: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number,
nm_doctor: PropTypes.string,
})
),
doctorModalOpen: PropTypes.bool,
}).isRequired,
members: PropTypes.shape({
membersModalOpen: PropTypes.bool,
}).isRequired,
};
static defaultProps = {
activeTeam: null,
};
state = {
nm_doctor: '',
spc_doctor: '',
address_doctor: '',
district_doctor: '',
city_doctor: '',
state_doctor: '',
ph1_doctor: '',
ph2_doctor: '',
ph3_doctor: '',
email: '',
website: '',
sus: '',
tj: '',
plan_doctor: '',
calldate_doctor: '',
contact_colih: '',
comments: '',
};
componentDidMount() {
const { getDoctorsRequest, activeTeam } = this.props;
if (activeTeam) {
getDoctorsRequest();
}
}
handleInputChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSearchChange = e => {
this.setState({ [e.target.name]: e.target.value });
const doctorlist = e.target.filter(doctors =>
doctors[e.target.name].includes(e.target.value)
);
this.setState(doctorlist);
};
handleCreateDoctor = e => {
e.preventDefault();
const { createDoctorRequest } = this.props;
const {
nm_doctor,
spc_doctor,
address_doctor,
district_doctor,
city_doctor,
state_doctor,
ph1_doctor,
ph2_doctor,
ph3_doctor,
email,
website,
sus,
tj,
plan_doctor,
calldate_doctor,
contact_colih,
comments,
} = this.state;
createDoctorRequest(
nm_doctor,
spc_doctor,
address_doctor,
district_doctor,
city_doctor,
state_doctor,
ph1_doctor,
ph2_doctor,
ph3_doctor,
email,
website,
sus,
tj,
plan_doctor,
calldate_doctor,
contact_colih,
comments
);
};
render() {
const {
activeTeam,
openDoctorModal,
closeDoctorModal,
doctors,
openMembersModal,
members,
} = this.props;
const {
nm_doctor,
spc_doctor,
address_doctor,
city_doctor,
district_doctor,
state_doctor,
ph1_doctor,
ph2_doctor,
ph3_doctor,
email,
website,
sus,
tj,
plan_doctor,
calldate_doctor,
contact_colih,
comments,
} = this.state;
if (!activeTeam) return null;
return (
<Container>
<header>
<h1>{activeTeam.name}</h1>
<div>
<Can checkPermission="doctors_create">
<Button onClick={openDoctorModal}>Cadastrar Médico</Button>
<Button onClick={openMembersModal}>Convidar Membro</Button>
</Can>
</div>
</header>
{/* Mostra lista dos médicos cadastrados */}
<SearchField
placeholder="Procurar por....."
onChange={this.handleSearchChange}
onClick={() => console.log('buscar médico!')}
/>
{/* <Searchbutton
onClick={() => console.log('Botão teste para editar médico!')}
size="26"
/> */}
{doctors.data.map(doctor => (
<Doctor key={doctor.id}>
<Editbutton
onClick={() => console.log('Botão teste para editar médico!')}
size="28"
/>
<ul>
<li>
<b>{doctor.nm_doctor}</b>
</li>
<li>{doctor.spc_doctor}</li>
<li>
{doctor.address_doctor} - {doctor.district_doctor}
</li>
<li>
{doctor.ph1_doctor} / {doctor.ph2_doctor} / {doctor.ph3_doctor}
</li>
<li>
{doctor.city_doctor} - {doctor.state_doctor}
</li>
<li>{doctor.email}</li>
<li>{doctor.website}</li>
<li>
<b>SUS: </b>
{doctor.sus} - <b>TJ: </b>
{doctor.tj}
</li>
<li>
<b>Convênio: </b>
{doctor.plan_doctor}
</li>
<li>
<b>Última Visita: </b>
{doctor.calldate_doctor}
</li>
<li>
<b>Contato Colih: </b>
{doctor.contact_colih}
</li>
<li>
<b>Observações: </b>
{doctor.comments}
</li>
</ul>
</Doctor>
))}
{/* Término - mostrar médicos cadastrados */}
{/* //Modal Cadastrar Médicos começa aqui// */}
{doctors.doctorModalOpen && (
<Modal>
<h1>Novo Médico</h1>
<form onSubmit={this.handleCreateDoctor}>
<span>Nome do médico</span>
<input
type="text"
name="nm_doctor"
value={nm_doctor}
onChange={this.handleInputChange}
/>
<span>Especialidade</span>
<input
name="spc_doctor"
value={spc_doctor}
onChange={this.handleInputChange}
/>
<span>Endereço</span>
<input
name="address_doctor"
value={address_doctor}
onChange={this.handleInputChange}
/>
<span>Bairro</span>
<input
name="district_doctor"
value={district_doctor}
onChange={this.handleInputChange}
/>
<span>Cidade</span>
<input
name="city_doctor"
value={city_doctor}
onChange={this.handleInputChange}
/>
<span>Estado</span>
<select
name="state_doctor"
value={state_doctor}
onChange={this.handleInputChange}
>
<MenuItem value="ST">Selecione....</MenuItem>
{/* <MenuItem value="AM">Rio de Janeiro</MenuItem> */}
<MenuItem value="SP">São Paulo</MenuItem>
</select>
<span>Telefone 1</span>
<input
name="ph1_doctor"
value={ph1_doctor}
onChange={this.handleInputChange}
/>
<span>Telefone 2</span>
<input
name="ph2_doctor"
value={ph2_doctor}
onChange={this.handleInputChange}
/>
<span>Telefone 3</span>
<input
name="ph3_doctor"
value={ph3_doctor}
onChange={this.handleInputChange}
/>
<span>Email</span>
<input
name="email"
value={email}
onChange={this.handleInputChange}
/>
<span>Website</span>
<input
name="website"
value={website}
onChange={this.handleInputChange}
/>
<span>SUS</span>
<select name="sus" value={sus} onChange={this.handleInputChange}>
<MenuItem value="ST">Selecione....</MenuItem>
<MenuItem value="Sim">Sim</MenuItem>
<MenuItem value="Não">Não</MenuItem>
</select>
<span>TJ</span>
<select name="tj" value={tj} onChange={this.handleInputChange}>
<MenuItem value="ST">Selecione....</MenuItem>
<MenuItem value="Sim">Sim</MenuItem>
<MenuItem value="Não">Não</MenuItem>
</select>
<span>Convênio</span>
<input
name="plan_doctor"
value={plan_doctor}
onChange={this.handleInputChange}
/>
<span>Última Visita</span>
<input
type="date"
name="calldate_doctor"
value={calldate_doctor}
onChange={this.handleInputChange}
/>
<span>Contato Colih</span>
<input
name="contact_colih"
value={contact_colih}
onChange={this.handleInputChange}
/>
<span>Observações</span>
<input
name="comments"
value={comments}
onChange={this.handleInputChange}
/>
<Savebutton size="big" type="submit">
Salvar
</Savebutton>
<Cancelbutton
onClick={closeDoctorModal}
size="small"
color="gray"
>
Cancelar
</Cancelbutton>
</form>
</Modal>
// Modal Cadastrar Médicos termina aqui//
)}
{members.membersModalOpen && <Members />}
</Container>
);
}
}
const mapStateToProps = state => ({
activeTeam: state.teams.active,
members: state.members,
doctors: state.doctors,
});
const mapDispatchToProps = dispatch =>
bindActionCreators({ ...DoctorsActions, ...MembersActions }, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(Doctors);
Error after typing in the search bar
Screen with search bar
e.target is the component that fired the event, you can't call filter on it. You probably want to get the full list of doctors from state and filter that.
In your constructor:
constructor(props) {
super(props);
// ...
// set initial state
// you will need to populate these from your backend and make sure to set filtered to the full list when you retrieve your list of doctors
this.state = {
doctorList: [],
filtered: [],
}
}
In your handleSearchChange function:
handleSearchChange = e => {
// get the search term
const searchTerm = e.target.value;
// filter the full list of doctors
const filtered = this.state.doctorList.filter(doctor => doctor.name.includes(searchTerm));
// set the filtered list as state
this.setState({filtered: filtered});
}
And then in your render function, take the filtered list from state and render from that.
render() {
return(
// ...
// render each doctor in the filtered list
this.state.filtered.forEach(doctor => <DoctorListElement doctor={doctor}/>);
// ...
);
}
I'm developing a dynamic component where the input can be used for several types: text, password, number, date, etc. The idea is to use this input, no matter the type and where to implement it, as long its adaptable. I thought using state was a nice idea, but I have no clue how to do this. Any thoughts?
import React, { Component } from 'react';
import './styles.css';
export default class InputField extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
password: false,
type: ''
}
}
render () {
return (
<div>
<label className='f-size'>{this.state.name}</label>
<input
className='input'
name={this.state.name}
placeholder={this.state.name}
value={this.props.value}
type={this.state.type}
onChange={this.props.onChange}
/>
<span className="errorMessage">{this.props.error}</span>
<span className="errorMessage">{this.props.missField}</span>
</div>
)
}
}
Thank you!
I personally think you should control this via props, seeing as the value will only be meaningful to the Input's parent.
I used this
const InputField = ({
name,
placeholder,
value,
type,
onChange,
error,
missField
}) => (
<div>
<label className="f-size">{name}</label>
<input
className="input"
name={name}
placeholder={placeholder}
value={value}
type={type}
onChange={onChange}
/>
<span className="errorMessage">{error}</span>
<span className="errorMessage">{missField}</span>
</div>
);
Parent component:
class App extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
state = {
value: '',
password: '',
};
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<div className="App">
<InputField
value={this.state.value}
type="number"
name="value"
onChange={this.handleChange}
/>
<InputField
value={this.state.password}
type="password"
name="password"
onChange={this.handleChange}
/>
</div>
);
}
}
Code Sandbox: https://codesandbox.io/s/y4ljv75k9
Edited to used a stateless component. Not sure if you want state to handle error messages but from your example, this is a valid solution.
<InputField type="text" />
<InputField type="password" />
<input
className='input'
name={this.state.name}
placeholder={this.state.name}
value={this.props.value}
type={this.props.type}
onChange={this.props.onChange}
/>
I would use props to change the type and manage the component.
You could then control the component from a form definition
You should use props not state, so you can pass
<InputType type="text" />
<InputType type="password" />
<InputType type="number" />
and for the other params you can use props also.
You could use this.props.type but the standard jsx input component is already dynamic as you can see from my example below :
var root = document.getElementById('root');
class InputField extends React.Component {
render() {
return (
<div>
<input type={this.props.type} />
</div>
)
}
}
class App extends React.Component {
render() {
return (
<div>
<input type='date' />
<InputField type='password'/>
</div>
)
}
}
ReactDOM.render(<App />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
Is there a reason why you would like to use a custom input component?
How to set defaultValue to input component?
<Field name={`${prize}.rank`} defaultValue={index} component={Input} type='text'/>
I tried like above but my fields are empty. I'm trying to create fieldArray (dynamic forms):
{fields.map((prize, index) =>
<div key={index} className="fieldArray-container relative border-bottom" style={{paddingTop: 35}}>
<small className="fieldArray-title marginBottom20">Prize {index + 1}
<button
type="button"
title="Remove prize"
className="btn btn-link absolute-link right"
onClick={() => fields.remove(index)}>Delete</button>
</small>
<div className="row">
<div className="col-xs-12 col-sm-6">
<Field name={`${prize}.rank`} defaultValue={index} component={Input} type='text'/>
<Field name={`${prize}.prizeId`} defaultValue={index} component={Input} type='text'/>
<Field
name={`${prize}.name`}
type="text"
component={Input}
label='Prize Name'/>
</div>
<div className="col-xs-12 col-sm-6">
<Field
name={`${prize}.url`}
type="text"
component={Input}
label="Prize URL"/>
</div>
<div className="col-xs-12">
<Field
name={`${prize}.description`}
type="text"
component={Input}
label="Prize Description" />
</div>
</div>
</div>
)}
On redux forms you can call initialize() with an object of values like so:
class MyForm extends Component {
componentWillMount () {
this.props.initialize({ name: 'your name' });
}
//if your data can be updated
componentWillReceiveProps (nextProps) {
if (/* nextProps changed in a way to reset default values */) {
this.props.destroy();
this.props.initialize({…});
}
}
render () {
return (
<form>
<Field name="name" component="…" />
</form>
);
}
}
export default reduxForm({})(MyForm);
This way you can update the default values over and over again, but if you just need to do it at the first time you can:
export default reduxForm({values: {…}})(MyForm);
This jsfiddle has an example
https://jsfiddle.net/bmv437/75rh036o/
const renderMembers = ({ fields }) => (
<div>
<h2>
Members
</h2>
<button onClick={() => fields.push({})}>
add
</button>
<br />
{fields.map((field, idx) => (
<div className="member" key={idx}>
First Name
<Field name={`${field}.firstName`} component="input" type="text" />
<br />
Last Name
<Field name={`${field}.lastName`} component="input" type="text" />
<br />
<button onClick={() => fields.remove(idx)}>
remove
</button>
<br />
</div>
))}
</div>
);
const Form = () => (
<FieldArray name="members" component={renderMembers} />
);
const MyForm = reduxForm({
form: "foo",
initialValues: {
members: [{
firstName: "myFirstName"
}]
}
})(Form);
this is my implementation using a HoC
import { Component } from 'react'
import {
change,
} from 'redux-form'
class ReduxFormInputContainer extends Component{
componentDidMount(){
const {
initialValue,
meta,
} = this.props
if(initialValue === undefined || meta.initial !== undefined || meta.dirty) return
const {
meta: { form, dispatch },
input: { name },
} = this.props
dispatch(change(form, name, initialValue))
}
render(){
const {
initialValue,
component: Compo,
...fieldProps
} = this.props
return <Compo {...fieldProps} />
}
}
function reduxFormInputContainer(component){
return function(props){
return <ReduxFormInputContainer {...props} component={component} />
}
}
export default reduxFormInputContainer
and then for exemple:
import reduxFormInputContainer from 'app/lib/reduxFormInputContainer'
InputNumericWidget = reduxFormInputContainer(InputNumericWidget)
class InputNumeric extends Component{
render(){
const props = this.props
return (
<Field component={InputNumericWidget} {...props} />
)
}
}