In React, using bootstrap modal how to edit and update State? - javascript

I have a table that shows a list of projects. When I click on a row to render a Modal, how do I prefill my input fields with data that I clicked on and then edit the fields so the state can be updated with the new data that I provide?
Here's my code breakdown with respective files:
Project.js
const Project = ({ companies, projects }) => {
return(
<div>
<section id={styles.project} className="divider overlay-light" data-bg-img="http://placehold.it/1920x1280">
<div className={`container ${styles.wrapper}`}>
<div className="row">
<div className={`col-md-12 ${styles['proj-header']}`}>
<h2 className="title">Projects</h2>
<button type="button" className={`btn ${styles['btn-project']}`} data-toggle="modal" data-target="#createProject">Create New Project</button>
{
companies.map((company, i) => {
return <CreateProjectModal key={i} company={company} />
})
}
</div>
</div>
<ManageColumns />
<div className="row">
<div className="col-md-12">
<div className={`${styles['table-responsive']} ${styles['dashboard-overview']} tableContainer`}>
<table className={`table table-striped scrollTable`}>
<thead className="fixedHeader">
<tr>
<th>Project Name <i className="fas fa-sort-amount-down"></i></th>
<th>Project Description</th>
<th>Action</th>
</tr>
</thead>
<tbody className="scrollContent">
{
projects.map((project, i) => {
return (
<tr key={i}>
<td>{project.project_name}</td>
<td>{project.description}</td>
<td>
<EditProjectModal projects={projects} />
</td>
</tr>
);
})
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
</div>
)
}
export default Project;
CreateProjectModal.js
class CreateProjectModal extends Component {
constructor(props) {
super(props);
this.state = {
project_name: '',
description: ''
}
}
onProjectNameChange(event) { this.setState({ project_name: event.target.value }); }
onDescriptionChange(event) { this.setState({ description: event.target.value }); }
handleSubmit(company) {
fetch(`http://localhost:5000/companys/${company._id['$oid']}/projects`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
project: {
project_name: this.state.project_name,
description: this.state.description
}
})
})
.then(response => response.json())
.then(data => { return data })
.catch(err => console.log(err));
}
render() {
const { company } = this.props;
return(
<div>
<div id="createProject" className="modal fade" tabIndex="-1" role="dialog">
<div className={`modal-dialog modal-lg ${styles['create-proj-modal']}`}>
<div className="modal-content">
<div className={`modal-header ${styles['create-proj-modal-header']}`}>
<button type="button" className={`close ${styles.closeModal}`} data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 className="modal-title" id="myModalLabel2">Create New Project</h3>
</div>
<div className={`modal-body ${styles['proj-modal-body']}`}>
<form>
<div className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label htmlFor="project-name" className="col-form-label">Project Name</label>
<input type="text" className="form-control" id="project-name" name="project_name" onChange={(e) => onProjectNameChange(e, this.state)} />
</div>
<div className={`form-group ${styles.formGroup}`}>
<label htmlFor="description" className="col-form-label">Description</label>
<textarea className="form-control" id="description" rows="4" name="description" onChange={(e) => onDescriptionChange(e, this.state)} ></textarea>
</div>
</form>
</div>
<div className={`modal-footer ${styles.modalFooter}`}>
<button type="button" className={`btn btn-primary text-white ${styles.saveBtn}`} onClick={() => handleSubmit(company)}>Save Project</button>
<button type="button" className={`btn btn-default ${styles.cancelBtn}`} data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateProjectModal;
EditProjectModal.js
class EditProjectModal extends Component {
constructor(props) {
super(props);
this.state = {
project_name: '',
description: ''
}
}
onProjectNameChange(event) { this.setState({ project_name: event.target.value }); }
onDescriptionChange(event) { this.setState({ description: event.target.value }); }
handleSubmit(project) {
fetch(`http://localhost:5000/projects/${project._id['$oid']}`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
project: {
project_name: this.state.project_name,
description: this.state.description
}
})
})
.then(response => response.json())
.then(data => { return data })
.catch(err => console.log(err));
}
render() {
const { project } = this.props;
return(
<div className="btn-group">
<NavLink type="button" to="#" className={`${styles['pencil-link']}`} data-toggle="modal" data-target="#editProject">
<i className={`fas fa-pencil-alt ${styles.pencil}`}></i>
</NavLink>
<div id="editProject" className="modal fade" tabIndex="-1" role="dialog">
<div className={`modal-dialog modal-lg ${styles['create-proj-modal']}`}>
<div className="modal-content">
<div className={`modal-header ${styles['create-proj-modal-header']}`}>
<button type="button" className={`close ${styles.closeModal}`} data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 className="modal-title" id="myModalLabel2">Edit Project</h3>
</div>
<div className={`modal-body ${styles['proj-modal-body']}`}>
<form>
<div className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label htmlFor="project-name" className="col-form-label">Project Name</label>
<input type="text" className="form-control" id="project-name" name="project_name" onChange={this.onProjectNameChange.bind(this)} />
</div>
<div className={`form-group ${styles.formGroup}`}>
<label htmlFor="description" className="col-form-label">Description</label>
<textarea className="form-control" id="description" rows="4" name="description" onChange={this.onDescriptionChange.bind(this)}></textarea>
</div>
</form>
</div>
<div className={`modal-footer ${styles.modalFooter} ${styles.editModalFooter}`}>
<button type="button" className={`btn btn-default ${styles.cancelBtn}`} data-dismiss="modal">Cancel</button>
<button type="button" className={`btn btn-primary text-white ${styles.saveBtn}`} onClick={(e) => this.handleSubmit(project)}>Save Changes</button>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default EditProjectModal;

First of all you need to pass the current row project details as a props to the EditProjectModal when you are filling the projects table (I named it theProject):
<tbody className="scrollContent">
{
projects.map((project, i) => {
return (
<tr key={i}>
<td>{project.project_name}</td>
<td>{project.description}</td>
<td>
<EditProjectModal projects={projects} theProject={project} />
</td>
</tr>
);
})
}
</tbody>
Then in the EditProjectModal, You can set it in the state like this:
constructor(props) {
super(props);
this.state = {
project_name: this.props.theProject.project_name,
description: this.props.theProject.description
}
}
}
Then you need to set the value of the inputs in the EditProjectModal with the state like this:
<form>
<div className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label htmlFor="project-name" className="col-form-label">Project Name</label>
<input type="text" className="form-control" id="project-name"
name="project_name"
value={this.state.project_name}
onChange={this.onProjectNameChange.bind(this)} />
</div>
<div className={`form-group ${styles.formGroup}`}>
<label htmlFor="description" className="col-form-label">Description</label>
<textarea className="form-control" id="description"
rows="4" name="description"
value={this.state.description}
onChange={this.onDescriptionChange.bind(this)}></textarea>
</div>
</form>

The edit form can be initialized by passing the row details as props to the EditProjectModal and the props can be assigned as state of EditProjectModal for making the handling easy.Then you can give value to the input and textarea using the value attribute.The value attribute can be given the corresponding state.
class EditProjectModal extends Component {
constructor(props) {
super(props);
this.state = {
project_name: '',
description: ''
}
}
ComponentWillMount() {
this.setState(project_name: this.props.project.project_name,description:this.props.project.description)
}
render() {
....//rest of the code
<form>
<div className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label htmlFor="project-name" className="col-form-label">Project Name</label>
<input type="text" className="form-control" id="project-name" name="project_name" onChange={this.onProjectNameChange.bind(this)} value={this.state.project_name}/>
</div>
<div className={`form-group ${styles.formGroup}`}>
<label htmlFor="description" className="col-form-label">Description</label>
<textarea className="form-control" id="description" rows="4" name="description" onChange={this.onDescriptionChange.bind(this)} value={this.state. description}/>
</div>
</form>
}
You need the pass the project as
<tbody className="scrollContent">
{
projects.map((project, i) => {
return (
<tr key={i}>
<td>{project.project_name}</td>
<td>{project.description}</td>
<td>
<EditProjectModal project={project} />
</td>
</tr>
);
})
}
</tbody>

Related

While clicking on Add Task Button my Bootstrap modal is not opening

Tysm for Solving in advance!
I think problem is in <button className="btn" onClick={handleDelete(todo.todo_id)}> in 52th line.
UncompletedTaskView.js is in App.js
import React,{useState} from 'react';
import axios from 'axios';
import AddTask from './AddTask';
import EditButton from './EditButton';
const UncompletedTaskView = () => {
const [todoList,setTodoList] = useState([]);
const [viewCompleted,setViewCompleted] = useState(false);
const refreshList = async () => {
try {
const response = await axios.get("http://localhost:8000/api/tasks/");
response.data.filter( (item) => item.completed === viewCompleted );
setTodoList(response.data);
} catch(err) {
console.log(err.message);
}
};
const handleDelete = async (id) => {
await axios.delete(`http://localhost:8000/api/tasks/${id}/`);
refreshList();
};
return (
<div className="container">
<h1 className='text-black text-uppercase text-center my-4'>Todo List</h1>
<table className="table table-hover">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Mark Completed</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{
todoList.map((todo) => {
return <tr id={todo.todo_id}>
<td>{todo.title}</td>
<td>{todo.description}</td>
<td className="radio">
<label><input type="radio" name="optradio" onClick={() => setViewCompleted(true)}/>Completed</label>
</td>
<td><EditButton refreshList={refreshList}/></td>
<td>
<button className="btn" onClick={handleDelete(todo.todo_id)}>
Delete
</button>
</td>
</tr>
})
}
</tbody>
</table>
<AddTask refreshList={refreshList}/>
</div>);
}
export default UncompletedTaskView;
AddTask.js File
import React,{ useState} from 'react';
import axios from 'axios';
const AddTask = ({ refreshList }) => {
const [title,setTitle] = useState("");
const [description,setDescription] =useState("");
const completed= false;
const handleSubmit = async() => {
const item = {
"title" : title,
"description": description,
"completed": completed
};
try {
await axios.post(`http://localhost:8000/api/tasks/`, item);
refreshList();
} catch (err) {
console.log(err.message);
}
}
return (<div>
<button
type="button"
className="btn btn-success"
data-toggle="modal"
data-target="#myModal">
Add Task
</button>
<div className="container">
<div className="modal fade" id="myModal" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">×</button>
<h4 className="modal-title">Add Task</h4>
</div>
<div className="modal-body">
<label htmlFor="title">Title</label>
<input
type="text"
name="title" value={title}
onChange={ (e) => setTitle(e.target.value)}
placeholder="Task Title" />
<label htmlFor="description">Title</label>
<input
type="text"
name="description" value={description}
onChange={ (e) => setDescription(e.target.value)}
placeholder="Task Description" />
</div>
<div className="modal-footer">
<button type="button" className="btn btn-success" onClick={handleSubmit}>Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>)
}
export default AddTask;
Tysm for Solving in advance!
I was using 3.37 but I replaced it with 4.3.1 and it's perfectly working!
#Suresh Thnx!

I try to get props to update a field but it not works (React)

I am trying to bring the props of my component, however when I open the edit modal it only brings the data of my first object. I want to bring them to EditForm so that I can update a field, but without the id and other data I can't do it.
When I click on the edit button it brings me the data correctly, it prints it in the console, it prints the data that corresponds to each user, but when passing it through props it only takes the data of the first user. When I open my Edit modal it pastes the data of the first user only, and not those of each user that the button corresponds
EditForm.js:
import React, { Component } from 'react'
export class PatchForm extends Component {
constructor(props){
super(props)
this.state = {
id: props.id,
name: props.name,
lastName: props.lastName,
age: props.age,
email: props.email,
salary: props.salary,
company: props.company,
image: props.image
}
}
changeHandler = e => {
this.setState({[e.target.name]: e.target.value})
}
render(){
const { name, lastName, age, email, salary, company, image} = this.state
return(
<div className="modal fade" id="editModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
<form>
<div className="form-group">
<label className="col-form-label">Name:</label>
<input type="text" className="form-control" name="name" value={name} onChange={this.changeHandler}></input>
</div>
<div className="form-group">
<label className="col-form-label">Last name:</label>
<input type="text" className="form-control" name="lastName" value={lastName} onChange={this.changeHandler}></input>
</div>
<div className="form-group">
<label className="col-form-label">Age:</label>
<input type="number" className="form-control" name="age" value={age} onChange={this.changeHandler}></input>
</div>
<div className="form-group">
<label className="col-form-label">Email:</label>
<input type="email" className="form-control" name="email" value={email} onChange={this.changeHandler}></input>
</div>
<div className="form-group">
<label className="col-form-label">Salary (MXNgit):</label>
<input type="number" className="form-control" name="salary" value={salary} onChange={this.changeHandler}></input>
</div>
<div className="form-group">
<label className="col-form-label">Company:</label>
<input type="text" readOnly className="form-control" name="company" placeholder={company} onChange={this.changeHandler}></input>
</div>
<div className="form-group">
<label className="col-form-label">URL img:</label>
<input type="text" className="form-control" name="company" value={image} onChange={this.changeHandler}></input>
</div>
{/* <button type="submit">Submit</button> */}
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" className="btn btn-primary" id="submitButton" onClick={() => {
window.location.reload()
}}>Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}
export default PatchForm
Table.jsx:
import React from 'react'
import PostForm from './PostForm'
import EditForm from './EditForm'
const EmployeesTable = () => {
// Estados
const [employee, setEmployee] = React.useState([])
const [currency, setCurrency] = React.useState(true)
// Ejecutamos la función en solo una ocasión con useEffect
React.useEffect( () => {
obtenerDatos()
}, [])
// Obtenemos los datos de los empleados
const obtenerDatos = async () => {
const data = await fetch('http://localhost:8080')
const employeesObject = await data.json()
const {employees} = employeesObject.data
setEmployee(employees)
}
// Formato de moneda
let formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'MXN',
});
let formatterUSD = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
return (
<div>
<div className="col-12 text-center">
<div className="col-12 col-lg-6 offset-lg-3">
{/* Condicional para cambiar entre false and true */}
<button className="btn m-2 btn-outline-success" onClick={() => setCurrency(!currency)}>Change Currency</button>
<button type="button" className=" m-2 btn btn-outline-success" data-toggle="modal" data-target="#createModal">Create Employee</button>
</div>
<table className="table table-dark text-center col-12 col-lg-6 offset-lg-3">
<thead className="thead-dark">
<tr>
<th scope="col">Total employees</th>
<th scope="col">Currency</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{employee.length}</th>
<th>{ currency ? "MXN" : "USD" }</th>
</tr>
</tbody>
</table>
</div>
{/* Form para creación de empleados */}
<PostForm />
<div className="table-wrapper-scroll-y my-custom-scrollbar">
<table className="table table-hover table-striped col-12">
<thead>
<tr>
<th>#</th>
<th>Avatar</th>
<th>Name</th>
<th>Last name</th>
<th>Age</th>
<th>Email</th>
<th>Salary {currency ? 'MXN' : 'USD'}</th>
<th>Company</th>
<th>Actions</th>
</tr>
</thead>
<tbody className="col-6">
{
// Iteramos para obtener los datos de cada empleado e imprimirlos en el DOM
employee.map((item, index) => {
return (
<tr key={item._id}>
<th>{index + 1}</th>
<td>
<img className="img-size" src={item.image} alt="img"/>
</td>
<td>{item.name}</td>
<td>{item.lastName}</td>
<td>{item.age}</td>
<td>{item.email}</td>
{/* Condicional para cambiar clase de color */}
<td className={ item.salary > 10000 ? "green text-right" : "red text-right"} >{ currency ? formatter.format(item.salary) : formatterUSD.format(item.salary * 21.5)}</td>
<td >{item.company}</td>
<td>
<EditForm
id={item._id}
name={item.name}
lastName={item.lastName}
age={item.age}
email={item.email}
salary={item.salary}
company={item.company}
image={item.image}
/>
<i className="fas fa-edit cursor-pointer" data-toggle="modal" data-target="#editModal" onClick={()=> {console.log(item._id)}}></i>
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
)
}
export default EmployeesTable;

Adding dynamic states in reactJs

I created a reactJs page that allows an admin add a user to a platform. Now, instead of submitting the form for each new user, the admin can add as many users as possible before submitting the form. By default, one table row containing input fields is displayed and then on click of the add button, a new row is added and the admin can fill the necessary details.
I want to add an onChange event to the input fields for each new row. I don't know how to do as this is quite dynamic. The state will have to change as new rows is added. I don't know how to go about updating this state and adding the onChange event for each field in each row. Here is my existing code:
export default class Admins extends React.Component{
constructor(props){
super(props);
this.state = {
errors : '',
success : '',
rows : [1]
}
this.addRow = this.addRow.bind(this);
this.fetchRows = this.fetchRows.bind(this);
this.removeRow = this.removeRow.bind(this);
}
addRow(){
var last = this.state.rows[this.state.rows.length-1];
var current = last + 1;
this.setState({
rows : this.state.rows.concat(current)
});
}
removeRow(index){
var array = this.state.rows;
array.splice(index, 1)
this.setState({
rows : array
})
}
fetchRows(){
return this.state.rows.map((row, index) => (
//console.log(row, index)
<tr key={row}>
<td className="text-center">
<button type="button" onClick={(e)=> this.removeRow(index)} data-toggle="tooltip" className="btn btn-xs btn-danger"
data-original-title=""><i className="fa fa-trash"></i>
</button>
</td>
<td>
<input type="text" className="form-control" onChange={}/>
</td>
<td>
<input type="text" className="form-control" onChange={}/>
</td>
<td>
<input type="text" className="form-control" onChange={}/>
</td>
</tr>
));
}
render(){
return(
<div>
<Top/>
<SideBar/>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item"><Link to="/">Dashboard</Link></li>
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5></h5>
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.fetchRows()}
<tr>
<td className="text-center">
<button type="button" onClick={this.addRow} data-toggle="tooltip" className="btn btn-xs btn-primary"
data-original-title=""><i className="fa fa-plus"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}
You could create a method onChange that takes in the event and the index of the row that got changed, and use the name and the value of the input that changed combined with the index of the row in the array to figure out what field to update.
Example
class Admins extends React.Component {
state = {
errors: "",
success: "",
rows: []
};
addRow = () => {
this.setState(previousState => {
return {
rows: [...previousState.rows, { name: "", email: "", password: "" }]
};
});
};
removeRow = index => {
this.setState(previousState => {
const rows = [...previousState.rows];
rows.splice(index, 1);
return { rows };
});
};
onChange = (event, index) => {
const { name, value } = event.target;
this.setState(previousState => {
const rows = [...previousState.rows];
rows[index] = { ...rows[index], [name]: value };
return { rows };
});
};
render() {
return (
<div>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5 />
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.state.rows.map((row, index) => (
<tr key={row}>
<td className="text-center">
<button
type="button"
onClick={e => this.removeRow(index)}
data-toggle="tooltip"
className="btn btn-xs btn-danger"
data-original-title=""
>
<i className="fa fa-trash" />
</button>
</td>
<td>
<input
type="text"
name="name"
className="form-control"
value={row.name}
onChange={e => this.onChange(e, index)}
/>
</td>
<td>
<input
type="text"
name="email"
className="form-control"
value={row.email}
onChange={e => this.onChange(e, index)}
/>
</td>
<td>
<input
type="text"
name="password"
className="form-control"
value={row.password}
onChange={e => this.onChange(e, index)}
/>
</td>
</tr>
))}
<tr>
<td className="text-center">
<button
type="button"
onClick={this.addRow}
data-toggle="tooltip"
className="btn btn-xs btn-primary"
data-original-title=""
>
<i className="fa fa-plus" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}

How can I update on reactjs fetch

Im trying to update my table row however it is not working the profile part is not reading the data inside tha input
this is the function i use for the update button
handleUpdate(id, name, address,department){
debugger
jQuery.support.cors = true;
function createNewProfile(profile) {
const formData = new FormData();
formData.append('Employee_Name', profile.name);
formData.append('Address', profile.address);
formData.append('department', profile.depatment);
return fetch('http://localhost:5118/api/employeedetails/PutEmployeeDetail/' +id, {
method: 'POST',
body: formData
})
.then(response => response.json())
}
createNewProfile(profile)
.then((json) => {
// handle success
})
.catch(error => error);
}
this is the part where is the form the input and the button
<div className="modal fade" id="UpdateEmployee" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">×</button>
<h4 className="modal-title">Update Employee</h4>
</div>
<form onSubmit={this.handleUpdate}>
<div className="container">
<div className="modal-body">
<table>
<tbody>
<tr>
<td>Name</td>
<td>
<input type="text"
name="Employee_Name"
value={this.state.Employee_Name}
onChange={(e) => this.handleChange(e)}/>
</td>
</tr>
<tr>
<td>Address</td>
<td>
<input type="text"
name="Address"
value={this.state.Address}
onChange={(e) => this.handleChange(e)}/>
</td>
</tr>
<tr>
<td>Department</td>
<td>
<input type="text"
name='Department'
value={this.state.Department}
onChange={(e) => this.handleChange(e)}/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="modal-footer">
<input type="submit" className="btn btn-info" onClick = { this.handleUpdate.bind(this, this.state.Employee_ID , this.state.Employee_Name ,this.state.Address ,this.state.Department)} value =" Add Employee"/>
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>

Fetch image from URL and set as background in React JS

I want to fetch the image from the URL and to display it.
I take the url as input in URL text field and when I use that in img tag it works like but when I pass or use it in td background it doesn't work
import React, { Component } from 'react';
class ImageStyle extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
url: '',
summary: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<div>
<div>
<h1 className="row px-2">Image Style Notification</h1>
<hr />
<div className="row px-1 py-2 animated fadeIn">
<div className="px-1" style={{ width:50 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Image URL"
name="url"
value={this.state.url}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Summary"
name="summary"
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
<br />
<div className="row px-2" >
<div>
<button className="nav-link btn btn-block btn-info" onClick={this.handleClick} >Save</button>
</div>
<div className="px-1">
<button className="nav-link btn btn-block btn-danger"> Cancel</button>
</div>
</div><br />
</div>
<div><br />
<div className="mobile">
<table className="table table-clear width-css">
<tbody>
<tr>
<td backgroundImage: 'url(${this.state.url})'>
<strong>
{this.state.title}
</strong><br />
{this.state.summary}<br />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default ImageStyle;
Specify the styles for the table and mention background image url like
backgroundImage: `url(${this.state.url})`
class ImageStyle extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
url: '',
summary: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
var styles = {
backgroundImage: `url(${this.state.url})`
}
return (
<div>
<div>
<h1 className="row px-2">Image Style Notification</h1>
<hr />
<div className="row px-1 py-2 animated fadeIn">
<div className="px-1" style={{ width:50 + '%' }}><br />
<div className="mb-1">
<input type="text"
className="form-control"
placeholder="Title"
name="title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Image URL"
name="url"
value={this.state.url}
onChange={this.handleInputChange}
/>
</div>
<div className="mb-1">
<textarea
className="form-control"
placeholder="Summary"
name="summary"
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
<br />
<div className="row px-2" >
<div>
<button className="nav-link btn btn-block btn-info" onClick={this.handleClick} >Save</button>
</div>
<div className="px-1">
<button className="nav-link btn btn-block btn-danger"> Cancel</button>
</div>
</div><br />
</div>
<div><br />
<div className="mobile">
<table className="table table-clear width-css">
<tbody>
<tr>
<td style={styles}>
<strong>
{this.state.title}
</strong><br />
{this.state.summary}<br />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
)
}
}

Categories