show last searched items below search form - javascript

I have a search form which is developed using redux form. I have used router to route to the form. After i submit the data from search form and revert back to the same form, i want to show a list of data that had been searched before whenever user clicks on search places input box. How can i do so?
Like in the image
Here is my code
const Banner = (props) => (
<Router>
<div className="container banner">
<ServiceType />
<div className="row">
<Match exactly pattern="/" location={props.location} component={Apartamentos} />
<Match pattern="/apartamentos" component={Apartamentos} />
<Match pattern="/coche" component={Coche} />
<Match pattern="/experiencias" component={Experiencias} />
</div>
</div>
</Router>
);
const renderGeoSuggestField = ({
input,
location
}) => (
<Geosuggest
fixtures={fixtures}
initialValue={input.value.label}
inputClassName="form-control destino"
onChange={(value) => input.onChange(value)}
onSuggestSelect={(value) => input.onChange(value)}
radius="20"
/>
);
const renderDateRangePicker = ({
input,
focusedInput,
onFocusChange,
}) => (
<DateRangePicker
onDatesChange={(start, end) => input.onChange(start, end)}
startDate={(input.value && input.value.startDate) || null}
endDate={(input.value && input.value.endDate) || null}
minimumNights={0}
/>
);
class ServiceType extends Component {
render() {
return(
div className="col-xs-12 col-sm-12 col-md-4 serviceImg">
<Link to="/apartamentos">
<img
src={imageUrl}
alt="apartamentos"
className="img-responsive"
/>
<h4>APARTAMENTOS</h4>
</Link>
</div>
);
}
}
class Apartamentos extends Component {
render() {
const { focusedInput } = this.state;
return (
<div className="form-box text-center">
<div className="container">
<form className="form-inline">
<div className="form-group">
<Field
name='geoSuggest'
component={renderGeoSuggestField}
onChange={(value) => this.onChange(value)}
onSuggestSelect={(suggest) => this.onSuggestSelect(suggest)}
location={new google.maps.LatLng(53.558572, 9.9278215)}
/>
</div>
<div className="form-group">
<Field
name="daterange"
onFocusChange={this.onFocusChange}
focusedInput={focusedInput}
component={renderDateRangePicker}
/>
</div>
<div className="form-group">
<Field
name="persona"
component="select"
>
<option>1 persona</option>
<option>2 personas</option>
</Field>
</div>
<button type="submit" className="btn btn-default buscar">BUSCAR</button>
</form>
</div>
</div>
);
}
}
const ApartmentForm = reduxForm({
form: 'ApartmentForm',
destroyOnUnmount: false,
})(Apartamentos);

What you should do is maintain is a redux state variable called say previousSearches which is initialized as an empty array. Everytime you click Submit push the form data into this previousSearches array. So when you click on the input button next just display all information from the previousSearches array (which is a redux variable and can be accessed as a prop).
Something like this I guess
case 'ADD_PREVIOUS_SEARCH':
return Object.assign({}, state, {
previousSearches: state.previousSearches.push(action.search)
})
Then you can just access previousSearches by this.props.previousSearches

Related

How to pass data between components in react?

I have been trying to display the form data submitted but the map is throwing an error.
I have two components
NameForm.js
Here is the form input, handlechange and handlesubmit methods are done
function Nameform() {
const [form, setForm] = useState({firstname: "", lastname: ""});
const handleChange = (e) => {
setForm({
...form,
[e.target.id]: (e.target.value),
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("hello from handle submit", form );
}
return (
<section>
<div className='card pa-30'>
<form onSubmit={ handleSubmit }>
<div className='layout-column mb-15'>
<label htmlFor='name' className='mb-3'>First Name</label>
<input
type='text'
id='firstname'
placeholder='Enter Your First Name'
data-testid='nameInput'
value={form.firstname}
onChange={handleChange}
/>
</div>
<div className='layout-column mb-15'>
<label htmlFor='name' className='mb-3'>First Name</label>
<input
type='text'
id='firstname'
placeholder='Enter Your First Name'
data-testid='nameInput'
value={form.firstname}
onChange={handleChange}
/>
</div>
<div className='layout-row justify-content-end'>
<button
type='submit'
className='mx-0'
data-testid='addButton'
>
Add Name
</button>
</div>
</form>
</div>
</section>
)
}
export default Nameform
NameList.js
I want to pass the data in handleSubmit in NameForm.js to NameList.js. But the data is not displayed.
function NameList({form}) {
return (
<section>
{form.map(displayName => {
return (
<ul
className='styled w-100 pl-0'
>
<li
className='flex slide-up-fade-in justify-content-between'
>
<div className='layout-column w-40'>
<h3 className='my-3'>{displayName.firstname}</h3>
<p className='my-0'{displayName.lastname}></p>
</div>
</li>
</ul>
)
})}
</section>
)
}
export default NameList;
App.js
In App.js, I want to display both the form and the data.
import { Nameform, Namelist } from './components'
function App() {
return (
<div>
<div className='layout-row justify-content-center mt-100'>
<div className='w-30 mr-75'>
<Nameform />
</div>
<div className='layout-column w-30'>
<NameList />
</div>
</div>
</div>
)
}
export default App;
Thank you for your help!
Pass the data you want to share between parent and children via props (which stands for properties).
In the parent class, when rendering <NameForm> and <ListForm> add the data like that:
//if you want to share count and name for example:
<NameForm
count={this.state.count}
name={this.state.name}
/>
You can add as many props as you want. Furthermore, you can pass a function and its argument using arrow functions:
<NameForm
aFunction={() => this.myFunction( /* anArgument */ )}
/>
To access props in a child class dynamically wherever you need them:
{this.props.count}
{this.props.name}
{this.props.aFucntion}
You can get rid of this.props using a technique called object destructing:
render(
const {count, name, aFunction} = this.props;
//now you can use {count} and {name} and {aFunction} without this.props
);
There are some bugs in your code, first form is an object not an array, so you can't map it, you need to use form.firstname and form.lastname, Also you set both input ids equal firstname you need to modify it, Also you need to move the form state and handleChange function to the App component.
This is a working code of your example.
https://codesandbox.io/s/upbeat-forest-328bon
You can save the state in the parent component and pass it as props to the child components like so.
Here we make use of an outer state called submittedForm to display only the submitted values. The inner form state is being used for handling the values before submitting.
// App.js
function App() {
const [submittedForm, setSubmittedForm] = useState({
firstname: "",
lastname: "",
});
return (
<div>
<div className="layout-row justify-content-center mt-100">
<div className="w-30 mr-75">
<NameForm setSubmittedForm={setSubmittedForm} />
</div>
<div className="layout-column w-30">
<NameList form={submittedForm} />
</div>
</div>
</div>
);
}
export default App;
// NameForm.js
function NameForm({ setSubmittedForm }) {
const [form, setForm] = useState({
firstname: "",
lastname: "",
});
const handleChange = (e) => {
// setActive(true);
setForm({
...form,
[e.target.id]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
setSubmittedForm(form);
};
return (
<section>
<div className="card pa-30">
<form onSubmit={handleSubmit}>
<div className="layout-column mb-15">
<label htmlFor="name" className="mb-3">
First Name
</label>
<input
type="text"
id="firstname"
placeholder="Enter Your First Name"
data-testid="nameInput"
value={form.firstname}
onChange={handleChange}
/>
</div>
<div className="layout-column mb-15">
<label htmlFor="name" className="mb-3">
Last Name
</label>
<input
type="text"
id="lastname"
placeholder="Enter Your Last Name"
data-testid="nameInput"
value={form.lastname}
onChange={handleChange}
/>
</div>
<div className="layout-row justify-content-end">
<button type="submit" className="mx-0" data-testid="addButton">
Add Name
</button>
</div>
</form>
</div>
</section>
);
}
export default NameForm;
// NameList.js
function NameList({ form }) {
return (
<section>
<ul className="styled w-100 pl-0">
<li className="flex slide-up-fade-in justify-content-between">
<div className="layout-column w-40">
<h3 className="my-3">{form.firstname}</h3>
<p className="my-0">{form.lastname}</p>
</div>
</li>
</ul>
</section>
);
}
export default NameList;

Changing variable in one file conflicts the data for other file in React JS

I'm having weird problem in React JS. I have two classes named as Notes.js and DataTables.js
I'm using DataTables in Note.js like this
<DataTables
keyField="id"
columns={columns}
url={this.state.url}
useCallBack={true}
onEdit={this.onEdit}
/>
Please Note that DataTables.js is my own custom created DataTable.js not react-datatable.
All the work like fetching data from URL and showing it in tabular form is in DataTables.js file.
Note.js Code:
import React, { Component } from "react";
import { Constant } from "../shared/Constants";
import DataTables from "../shared/DataTables";
import { Modal, Button } from "react-bootstrap";
import BreadCrumb from "../shared/BreadCrumb";
import "../Style.css";
const columns = Constant.notes;
export class Notes extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
url: "notes/get_notes",
showModal: false,
note: [],
};
this.onEdit = this.onEdit.bind(this);
this.onAdd = this.onAdd.bind(this);
this.onUpdate = this.onUpdate.bind(this);
this.saveNote = this.saveNote.bind(this);
}
onUpdate(key, value) {
let noteData = this.state.note;
noteData[key] = value;
this.setState({
note: noteData,
});
}
saveNote(e) {
e.preventDefault();
}
onEdit(n) {
this.setState({
note: n,
showModal: true,
});
}
onAdd() {
this.setState({
note: [],
showModal: true,
});
}
render() {
return (
<>
<Modal
show={this.state.showModal}
aria-labelledby="example-modal-sizes-title-lg"
onHide={() => this.setState({ showModal: false })}
>
<form method="post" onSubmit={this.saveNote}>
<Modal.Header>
<Modal.Title>My Note</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="row">
<div className="col-sm-12">
<div className="form-group">
<label className="text-muted">Note Title</label>
<input
type="text"
placeholder="Note Title"
className="form-control"
ref="title"
value={this.state.note.title}
onChange={(e) => this.onUpdate("title", e.target.value)}
/>
</div>
<div className="form-group">
<label className="text-muted">Content</label>
<textarea
onChange={(e) => this.onUpdate("content", e.target.value)}
className="form-control"
style={{ height: "250px" }}
placeholder="Content"
>
{this.state.note.content}
</textarea>
</div>
</div>
</div>
</Modal.Body>
<Modal.Footer>
<Button
variant="secondary"
onClick={() => this.setState({ showModal: false })}
>
Close
</Button>
<Button type="submit" variant="primary">
Save Note
</Button>
</Modal.Footer>
</form>
</Modal>
<BreadCrumb
title="My Notes"
useCallBack={true}
onAdd={this.onAdd}
active_link="Notes"
link=""
link_text="Add New"
/>
<div className="row">
<div className="col-sm-12">
<div className="card">
<div className="card-body">
<div className="card-title">Notes</div>
<DataTables
keyField="id"
columns={columns}
url={this.state.url}
useCallBack={true}
onEdit={this.onEdit}
/>
</div>
</div>
</div>
</div>
</>
);
}
}
export default Notes;
I'm having Problem in Note.js on onUpdate function
onUpdate(key, value) {
let noteData = this.state.note;
noteData[key] = value;
this.setState({
note: noteData,
});
}
Problem: When I update a field in Modal as you can see in my code, then my Table in DataTable.js automatically gets updated, I'don't why :/
Here is DataTables.js function where I'm sending data to onEdit function
const TableData = () => {
return (
<tbody>
{tableData.length === 0 ?
<tr>
<td className="text-center" colSpan="5"><strong>No Data Found</strong></td>
</tr>
:
tableData.map((tData) => (
<tr key={tData[this.props.keyField]}>
{this.props.columns.map((item, index) => (
<td key={index} className="table-content">
{index === 0 ?
[(useCallback === true ? <span key={"sub_"+index} className="link" onClick={() => this.props.onEdit(tData)}>{tData[item.dataField]}</span> :
<Link
to={
this.props.edit_link +
"/" +
tData[this.props.edit_key_first] + (this.props.edit_key_second ? "/" +
tData[this.props.edit_key_second] : '')
}
>
{tData[item.dataField]}
</Link>
)]
: (
tData[item.dataField]
)}
</td>
))}
</tr>
))}
</tbody>
);
};
Please check gif image below so you can understand it :P
You have an onChange function that is updating the content
onChange={(e) => this.onUpdate("content", e.target.value)}
If you don't want to change the content while typing then you will have to remove this.

Refactor dropdown component in React

I have to use multiple dropdowns from semantic-ui-react in my project. They need to have different props. It looks like this
<div className="wrapper">
<img className="icon" src={iconA} alt="iconA"></img>
<h1>A</h1>
<Dropdown
className="dropdown"
search
selection
options={optionsA}
placeholder="A"
defaultValue="A"
onChange={handleAChange}
/>
</div>
<div className="wrapper">
<img className="icon" src={iconB} alt="iconB"></img>
<h1>B</h1>
<Dropdown
className="dropdown"
search
selection
options={optionsB}
placeholder="B"
defaultValue="B"
onChange={handleBChange}
/>
</div>
I want to refactor this and create a single component for this by pasing different props. Please guide me on how this can be refactored in the best way possible.
First, create your custom dropDown component and extract props using object destructuring, you can give deafult values to props there itself, but better use PropTypes for that.
const CustomDropDown = (props) => {
const {
className,
search,
selection,
options,
placeholder,
defaultValue,
onChange
} = props;
return (
<div className="wrapper">
<img className="icon" src={iconA} alt="iconA"></img>
<h1>A</h1>
<Dropdown
className={classname}
search={search}
selection={selection}
options={optionsA}
placeholder={placeholder}
defaultValue={defaultValue}
onChange={onChange}
/>
</div>
)
}
Now, call the component like this,
<CustomDropDown
className="dropdown"
search
selection
options={optionsA}
placeholder="A"
defaultValue="A"
onChange={handleAChange}
/>
You can do it as follows:
const DropDownWraper = ({
header,
options,
onChange,
iconProps,
placeholde,
defaultValue
}) =>
<div className="wrapper">
<img
className="icon"
src={ iconProps.src }
alt={ iconProps.alt } />
<h1>{ header }</h1>
<Dropdown
search
selection
options={ options }
className="dropdown"
onChange={ onChange }
placeholder={ placeholde }
defaultValue={ defaultValue } />
</div>

Delete a <div> onClick in React

I would like to delete a search result by clicking on the X icon on the individual card.
The search returns 10 recipes from the API, generating 10 divs. How would I go about removing individual divs onClick of the icon whilst keeping the other divs? Essentially just a remove search result button.
return (
<div className='App'>
<form onSubmit={getSearch} className="search-form">
<InputGroup>
<InputGroupAddon addonType="prepend">
<InputGroupText><FontAwesomeIcon icon={faSearch} /></InputGroupText>
</InputGroupAddon>
<Input className="search-bar" type="text" placeholder="Search for recipe..." value={search} onChange={updateSearch} />
</InputGroup>
<Button color="primary" size="sm" className="search-button" type="submit">Search</Button>
</form>
<div className="recipes">
{recipes.map(recipe => (
<Recipe
key={recipe.recipe.label}
title={recipe.recipe.label}
theUrl={recipe.recipe.url}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
source={recipe.recipe.source}
healthLabels={recipe.recipe.healthLabels}
servings={recipe.recipe.yield} />
))}
</div>
</div>
const Recipe = ({ title, theUrl, image, ingredients, source, healthLabels, servings }) => {
return (
<div className={style.recipe}>
<FontAwesomeIcon className={style.delete} icon={faTimes} />
<h3 >{title}</h3>
<Badge className={style.badge} color="primary">{source}</Badge>
<p>Serves: <Badge color="primary" pill>{servings}</Badge></p>
<img src={image} alt='food' />
<ol className={style.allergens}>
{healthLabels.map(healthLabel => (
<li>{healthLabel}</li>
))}
</ol>
<div className={style.ingr}>
<ol>
{ingredients.map(ingredient => (
<li>{ingredient.text}</li>
))}
</ol>
<Button className={style.button} outline color="primary" size="sm" href={theUrl} target="_blank">Method</Button>
</div>
<div className={style.info}>
<div className={style.share}>
<WhatsappShareButton url={theUrl}><WhatsappIcon round={true} size={20} /></WhatsappShareButton>
<FacebookShareButton url={theUrl}><FacebookIcon round={true} size={20} /></FacebookShareButton>
<EmailShareButton url={theUrl}><EmailIcon round={true} size={20} /></EmailShareButton>
</div>
</div>
</div>
);
}
Simply update the recipes array and React will update the HTML.
I'm not sure where recipes comes from, but if you set an onClick on, say, <Recipe label="x"> that deletes the corresponding recipe element from recipes, then React should no longer render that recipe.
That should be easy. Here's one way:
add onClick to this
<FontAwesomeIcon onClick={deleteRecipe} className={style.delete} icon={faTimes} />
pass a reference of the function that deletes the recipe.
deleteRecipeHandler = (id) => {
// filter your recipes here such that the new recipes array doesn't contain the recipe
// with the id you're getting here.
// Change the below code how you need
const newRecipes = oldRecipes.filter(recipe => {
return recipe.id !== id;
});
}
{recipes.map(recipe => (
<Recipe
key={recipe.recipe.label}
deleteRecipe={this.deleteRecipeHandler.bind(this,recipe.recipe.id)}
title={recipe.recipe.label}
theUrl={recipe.recipe.url}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
source={recipe.recipe.source}
healthLabels={recipe.recipe.healthLabels}
servings={recipe.recipe.yield} />
))}
since you're destructuring your props you can use
const Recipe = ({ title, theUrl, image, ingredients, source, healthLabels, servings, deleteRecipe }) => {
return (
<div className={style.recipe}>
<FontAwesomeIcon onClick={deleteRecipe} className={style.delete} icon={faTimes} />

Redux Forms for Creating and Editing

I am working with redux-form. I need to create a new user and update the user's information using the same form. I've made the required form to create a new user right now, but I don't know how to make it available for updating.
Form Component code:
class UserRegistrationForm extends PureComponent {
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired,
isLoading: PropTypes.bool,
submitting: PropTypes.bool.isRequired,
};
constructor() {
super();
this.state = {
showPassword: false,
};
}
showPassword = (e) => {
e.preventDefault();
this.setState(prevState => ({ showPassword: !prevState.showPassword }));
};
onSubmit = data => {
console.log(data);
}
render() {
const { handleSubmit, reset } = this.props;
return (
<Col md={12} lg={12}>
<Card>
<CardBody>
<div className="card__title">
<h5 className="bold-text">STUDENT INFORMATION</h5>
</div>
<form className="form form--horizontal" onSubmit={handleSubmit}>
<div className="form__form-group">
<span className="form__form-group-label">First Name*</span>
<div className="form__form-group-field">
<Field
name="name"
component="input"
type="text"
placeholder="Name"
/>
</div>
</div>
<div className="form__form-group">
<span className="form__form-group-label">Last Name*</span>
<div className="form__form-group-field">
<Field
name="surname"
component="input"
type="text"
placeholder="Surname"
/>
</div>
</div>
<div className="form__form-group">
<span className="form__form-group-label">E-mail*</span>
<div className="form__form-group-field">
<Field
name="email"
component="input"
type="email"
placeholder="example#mail.com"
/>
</div>
</div>
<ButtonToolbar className="form__button-toolbar">
<Button color="primary" type="submit" className="icon" size="sm"><SendIcon /> Submit</Button>
<Button type="button" onClick={reset} className="icon" size="sm">
<CloseIcon /> Cancel
</Button>
</ButtonToolbar>
</form>
</CardBody>
</Card>
</Col>
);
}
}
export default reduxForm({
validate,
form: 'User_Registration_Form', // a unique identifier for this form
})(withTranslation('common')(UserRegistrationForm));
How can I make the form both available creating and updating?
To use the same form for the update as well, you would need to give an initialValues state to Form. Where initial values would be the value of the student you want to edit. Initialize values would be empty when you are creating a new student.
UserRegistrationForm = reduxForm({
validate,
form: 'User_Registration_Form', // a unique identifier for this form
})(withTranslation('common')(UserRegistrationForm));
InitializeFromStateForm = connect(
state => ({
initialValues: studentData
}),
)(InitializeFromStateForm)
export default UserRegistrationForm
An example is here https://redux-form.com/6.6.3/examples/initializefromstate/
Also in your react route file, try to maintain two routes with the same form component.
<Route path="/student/create" component={UserRegistrationForm} />
<Route path="/student/update/:id" component={UserRegistrationForm} />
So whenever you need to create, you redirect to create route and when you need to update, redirect it to update route, with an id as params.

Categories

Resources