Is it possible to to make this delete button and input form work? - javascript

So iv been stuck for quite some time now, i need to make my delete button work on every row and make inputs spit info to my table.
My question is : Is it even possible to do it? (I just started to learn react/js literally today).
The final product should look like "to do list" but when i open it it automatically has values from api that i can delete and add new.
My code:
export default class FetchRandomUser extends React.Component {
state = {
loading: true,
people: []
};
async componentDidMount() {
const url = "https://swapi.dev/api/people/";
const response = await fetch(url);
const data = await response.json();
const pirmadata = data;
this.setState({ people: pirmadata.results, loading: false });
console.log(pirmadata)
}
render() {
if (this.state.loading) {
return <div>loading...</div>;
}
if (!this.state.people.length) {
return <div>didn't get a person</div>;
}
return (
<div className="listas">
{this.state.people.map(person => (
<tr className="taras" key={person.name + person.age}>
<th className="name">{person.name}</th>
<th className="birth">{person.birth_year}</th>
<th className="genders">{person.gender}</th>
<th><button type="submit" className="delete">Delete</button></th>
</tr>
))}
</div>
);
}
}
My form is made on different .js file and basically is a function which holds this form:
<div className="forma">
<form>
<input type="text" placeholder="Enter name :"></input>
<input type="text" placeholder="Enter birth date :"></input>
<input type="text" placeholder="Enter gender :"></input>
<button type="submit">Submit entry!</button>
</form>
</div>

Add a click handler for the Delete button that is the onSubmit handler of the form element. That way when you click it, it will call the form's handler function.
Pass the handlerFunc to the component with the th elements as a prop to be able to use it as the following:
function YourComponent({ handler }){
return <th><button onClick={handler} className="delete">Delete</button></th>);
}
Form onSubmit handler:
<form onSubmit={handlerFunc}>
<input type="text" placeholder="Enter name :"></input>
<input type="text" placeholder="Enter birth date :"></input>
<input type="text" placeholder="Enter gender :"></input>
<button type="submit">Submit entry!</button>
</form>
<YourComponent handler={handlerFunc} />

Related

Form not passing value on submit

I am struggling with getting my results from an API to show up on HTML page. Does work if the function is executed in the console.
<body>
<div>
<form>
<input type="text" id="search" placeholder="Enter person">
<input type="submit" value="Submit" name="submit" onclick="fetchPerson()" />
</form>
</div>
<div id="app"></div>
JS:
function fetchPerson() {
var input = document.getElementById('search').value;
fetch(`notrevealingapi/api/name=${input}`)
.then(res => res.json())
.then(data => {
console.log(data);
const html = data.data
.map(hit => {
return `<p>Hits: ${hit.person}</p>`;
})
.join("");
document.querySelector('#app').insertAdjacentHTML("afterbegin", html);
})
}
If I understand your need correctly.
you want to populate the result in the <div id="app"> when a user clicks on the submit button.
There is two basic mistakes I can think of.
You should use the button type instead of submit
And use innerHTML instead of the insertAdjacentHTML. So it would look like
document.querySelector('#app').innerHTML = html

How do I send data from a WYSIWYG to a database (Vue.js)

I just started using the Vue2Editor with the intention to replace the many forms that I use to send text and image data to my Firebase database.
My problem is that I cannot get it to add the data entered in the editor.
When using forms, I would just attach an event handler to the form itself and make a function that allowed the transfer.
Example:
<form #submit.prevent="addText">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" v-model="fname">
</form>
<button type="submit" variant="success">Save</button>
But when using the Vue2Editor, I do not get any form tags.
I just get a "vue-editor" tag. I tried adding the event handler inside this tag, but nothing happens.
I don't get any errors, but the data is not transferred to the database upon submitting it.
This is the code:
<template>
<div class="container">
<div class="text_editor">
<h2>Add new content</h2>
<vue-editor #submit.prevent="addText" v-model="textblock" />
<button type="submit" class="textblock_btn" variant="success">Save</button>
</div>
</div>
</template>
<script>
import db from '#/firebase/init'
import Vue from "vue";
import Vue2Editor from "vue2-editor";
Vue.use(Vue2Editor);
export default {
name: 'textblock',
data () {
return {
textblock: null
}
},
methods: {
addText(){
db.collection('textblock').add({
textblock: this.textblock
}).then(() => {
this.$router.push({ name: 'Index' })
}).catch(err => {
console.log(err)
})
}
}
}
</script>
You can still wrap the component in a form as the WYSIWYG editor's data is bound to the v-model property.
<form #submit.prevent="addText">
<div class="text_editor">
<h2>Add new content</h2>
<vue-editor v-model="textblock" />
<button type="submit" class="textblock_btn" variant="success">Save</button>
</div>
</form>
Within the addText method you now have this.textblock with the appropriate data on form submission.

How to set the default value of a dropdown list to a state variable in Reactjs

I have a React component which contains a textbox, dropdown list, and a submit button.
I capture values of the textbox and a dropdown list using an 'OnChange' event as follows.
<div className="form-group">
<label htmlFor="accountName">Account Name</label>
<input type="text" id="accountName" className="form-control" name="accountName" value={this.state.accountName} onChange={(e)=>this.change(e)}></input>
</div>
<div className="form-group">
<label htmlFor="originatedBy">Originated By</label>
<select className="form-control" id="originatedBy" name="originatedBy" value={this.state.originatedBy} onChange={(e)=>this.change(e)}>
<option>value1</option>
<option>value2</option>
<option>value3</option>
</select>
</div>
<div className="form-group row ml-md-1">
<button type="submit" className="btn btn-outline-primary btn-block" onClick={(e)=>this.addRecord(e)}>Add Record</button>
</div>
And in the Js section, I have,
class AddRecordView extends Component{
state={
accountName:"",
originatedBy:""
}
change(e){
this.setState({[e.target.name]:e.target.value});
}
addRecord(e){
e.preventDefault(e);
const user={
accountName : this.state.accountName,
originatedBy : this.state.originatedBy,
}
console.log(user);
var url = <url_of_the_endpoint>";
axios.post(url, {
user
},{
headers: {
'Accept': 'application/json'
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
}
render(){
return(
<html_section>
);
}
}
export default AddRecordView;
The 'accountName' and the 'originatedBy' values are simply set when there is a change in the textbox and dropdown-list respectively.
However, if I let the default value (the value which shows when the form is loaded) of the dropdown-list remains unchanged and Submit the data, it doesn't trigger the 'OnChange' event and passes,
{accountName: 'some_value', originatedBy: ""} to the backend.
How can I make the 'originatedBy' attribute to take the default value of the dropdown-list. Please share your ideas on how to make it work (maybe from the constructor or any other suitable method).
Any suggestions will be helpful.

Generate element from submit React.js

I'd like to generate some HTML to show sucessfull form submission. I can't seem to do it within the handleSubmit Method.
class BookingForm extends Component{
...
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
console.log(name + ' '+value);
this.setState({
[name]: value
});
}
Submit method that I'd like to render html:
handleSubmit(event) {
console.log(this.state.lessonTime)
event.preventDefault();
this.setState({'success':true})
return(
<h1>Success</h1>
);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<TimeList defaultTime={this.state.defaultTime}
handleChange={this.handleChange}/>
<br/>
<DateList defaultDate={this.state.defaultDate}
handleChange={this.handleChange}/>
<br/>
<NumberOfLessons defaultNOL={this.state.defaultLessons}
handleChange={this.handleChange}/>
<br/>
<input type="submit" value="Book Lesson" />
</form>
<br/>
</div>
);
}
}
Any ideas on how I can get the success heading to show once submit has been clicked on.
Thanks
I think a better way to handle this is to use state to control the rendering of "success" heading. You can add the following line of code to the place you want to add the header:
{this.state.success && <div> Successful </div> }
I think the reason the html tag returned by handleSubmit in your function doesn't show up is because although it returns the tag, it doesn't know where to put it. If you want to make it work, you'll need to use methods like createElement and appendChild but that's not the way react should work.
If you want your <h1> element to render instead of form on successful completion do this in your render function:
render() {
return (
<div>
{this.state.success?(
<h1>Success</h1>
):(
<form onSubmit={this.handleSubmit}>
<TimeList defaultTime={this.state.defaultTime}
handleChange={this.handleChange}/>
<br/>
<DateList defaultDate={this.state.defaultDate}
handleChange={this.handleChange}/>
<br/>
<NumberOfLessons defaultNOL={this.state.defaultLessons}
handleChange={this.handleChange}/>
<br/>
<input type="submit" value="Book Lesson" />
</form>
<br/>)}
</div>
);
}

Multiple Registration Form with redux and react

I have been trying to develop a dashboard form similiar to airbnb listing form for understanding more deeply about react redux but i am stuck in the middle of my project. I have a multiple form where when user clicks on continue button the user will get another form to fill and so on and if user clicks on back button the user will get form of one step back with previously filled values. I could not decide what should i do for this. Do i have to create a object in action as listingName . summary, name, email etc as empty value and update it with reducer using Object.assign() or what. Till now i could only develop like when user clicks on personal tab a form related to personal information is shown and when user clicks on basic tab, a form related to basic information is shown. I want all form data to be send to server at last submit. What should i do now ? Do i use increment and decrement action for the continue and back button and use submit action on the last form button ? Could you please provide me an idea ?
Here's my code
actions/index.js
export function selectForm(form){
return{
type: 'FORM_SELECTED',
payload: form
};
}
reducers/reducer_active_form.js
export default function(state=null, action){
let newState = Object.assign({},state);
switch(action.type){
case 'FORM_SELECTED':
return action.payload;
}
return state;
}
reducers/reducer_form_option.js
export default function(){
return[
{ option: 'Personal Information', id:1},
{ option: 'Basic Information', id:2 },
{ option: 'Description', id:3},
{ option: 'Location', id:4},
{ option: 'Amenities', id:5},
{ option: 'Gallery', id:6}
]
}
containers/form-details
class FormDetail extends Component{
renderPersonalInfo(){
return(
<div className="personalInfo">
<div className="col-md-4">
<label htmlFor='name'>Owner Name</label>
<input ref="name" type="textbox" className="form-control" id="name" placeholder="Owner name" />
</div>
<div className="col-md-4">
<label htmlFor="email">Email</label>
<input ref="email" type="email" className="form-control" id="email" placeholder="email" />
</div>
<div className="col-md-4">
<label htmlFor="phoneNumber">Phone Number</label>
<input ref="phone" type="textbox" className="form-control" id="phoneNumber" placeholder="phone number" />
</div>
<div className="buttons">
<button className="btn btn-primary">Continue</button>
</div>
</div>
);
}
renderBasicInfo(){
return(
<div>
<h3>Help Rent seekers find the right fit</h3>
<p className="subtitle">People searching on Rental Space can filter by listing basics to find a space that matches their needs.</p>
<hr/>
<div className="col-md-4 basicForm">
<label htmlFor="price">Property Type</label>
<select className="form-control" name="Property Type" ref="property">
<option value="appartment">Appartment</option>
<option value="house">House</option>
</select>
</div>
<div className="col-md-4 basicForm">
<label htmlFor="price">Price</label>
<input type="textbox" ref="price" className="form-control" id="price" placeholder="Enter Price" required />
</div>
<div className="buttons">
<button className="btn btn-primary">Back</button>
<button className="btn btn-primary">Continue</button>
</div>
</div>
);
}
renderDescription(){
return(
<div>
<h3>Tell Rent Seekers about your space</h3>
<hr/>
<div className="col-md-6">
<label htmlFor="listingName">Listing Name</label>
<input ref="name" type="textbox" className="form-control" id="listingName" placeholder="Be clear" />
</div>
<div className="col-sm-6">
<label htmlFor="summary">Summary</label>
<textarea ref="summary" className="form-control" id="summary" rows="3"></textarea>
</div>
<div className="buttons">
<button className="btn btn-primary">Back</button>
<button className="btn btn-primary">Continue</button>
</div>
</div>
);
}
renderLocation(){
return(
<div>
<h3>Help guests find your place</h3>
<p className="subtitle">will use this information to find a place that’s in the right spot.</p>
<hr/>
<div className="col-md-6">
<label htmlFor="city">City</label>
<input ref="city" type="textbox" className="form-control" id="city" placeholder="Biratnagar" />
</div>
<div className="col-md-6">
<label htmlFor="placeName">Name of Place</label>
<input ref="place" type="textbox" className="form-control" id="placeName" placeholder="Ganesh Chowk" />
</div>
<div className="buttons">
<button className="btn btn-primary">Back</button>
<button className="btn btn-primary">Continue</button>
</div>
</div>
);
}
render(){
if ( !this.props.form){
return this.renderPersonalInfo();
}
const type = this.props.form.option;
console.log('type is', type);
if ( type === 'Personal Information'){
return this.renderPersonalInfo();
}
if ( type === 'Basic Information'){
return this.renderBasicInfo();
}
if ( type === 'Description'){
return this.renderDescription();
}
if ( type === 'Location'){
return this.renderLocation();
}
}
}
function mapStateToProps(state){
return{
form: state.activeForm
};
}
export default connect(mapStateToProps)(FormDetail);
The first thing you're missing is controlled components. By giving the inputs a value property, and an onChange function, you will link the input with an external state.
Your components should have access, via react-redux, to the state and actions needed. The value of the form should be your state for that object. So you might have a state like:
location: {
listingName: '123 Main St',
summary: 'The most beautiful place!'
}
Then, you'd just pass each property to inputs. I'm assuming, in this example, that you've passed the location prop in mapStateToProps, and an actions object with all the related actions in mapDispatchToProps:
changeHandler(ev, fieldName) {
const val = ev.target.value;
this.props.actions.updateField(fieldName, val);
},
render() {
return (
<input
value={this.props.location.listingName}
onChange={(ev) => { this.changeHandler(ev, 'listingName'}}
/>
);
}
You provide it an action that can be used to update the state:
function updatefield(field, val) {
return {
type: UPDATE_FIELD,
field,
val
};
}
Then, you just merge it in, in your reducer
switch (action.type) {
case UPDATE_FIELD:
state = { ...state, [action.field]: val };
(using dynamic keys and spread operator for neatness, but it's similar to Object.assign)
All of your form state lives in the Redux store this way. When you are ready to submit that data to the server, you can either use async actions with redux-thunk, or set up some middleware to run the calls. Either way, the strategy is the same; your state lasts locally and populates all your forms, and then is sent to the server when the user submits.
I went through this pretty quick, let me know if you need me to elaborate on anything :)
As you are using react-redux you can use the redux-form. It will greatly help you with the coding as it will simplify your work load and it is also bug-free (as far as I know). In my opinion you would want to use all the libraries/frameworks provided to you as you want to be as agile as possible.
Also the redux-form has a wizard form implementation. I think that is exactly what you are looking for.
http://erikras.github.io/redux-form/#/examples/wizard?_k=yspolv
Just follow the link and you will see a very good tutorial on how to implement it. Should be a piece of cake.

Categories