React | How to add dynamic new divs like rows
You can manage this through an array
, add items in array
when rows are added and remove them accordingly. You can do the following
class App extends React.Component {
constructor() { super(); this.state = { rowList: [true] }; }
add() { let rowList = [...this.state.rowList]; rowList.push(true); this.setState({ rowList }); }
remove(i) { let rowList = [...this.state.rowList]; rowList.splice(i, 1); this.setState({ rowList }); }
render() { let { rowList } = this.state; return ( <div className="intent" id="intent1" style={{border:'1px solid #eee'}}> {rowList.map((x, i) => { return ( <div className="form-group row" key={i}> <label htmlFor="intent" className="col-sm-1 col-form-label"> Intent </label> <div className="col-sm-5"> <input type="text" className="form-control" name="indent[]" placeholder="Enter intent" /> <button onClick={() => this.remove(i)} >Remove</button> </div> </div> ) })} <button onClick={() => this.add()}>Add New</button> </div> ); }}
ReactDOM.render(<App />, document.getElementById('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>
How to create dynamic Row using loop in JSX?
You need to do another loop for your BlogItems. For each row, you want 3 BlogItems. The outer map takes care of the rows, the inner map takes care of the BlogItems.
To get your alternating classNames for the column widths, you can pass a new prop that tells the BlogItem if the row it's in is in an even place or not.
<Container>
{articles.map((art, i) =>
(i + 1) % 3 === 0 ? (
<Row>
{" "}
<></>
{Array(3).fill().map((el, index) => {
return <BlogItem index={index} even={i % 2 === 0} colNum={3} art={art} />
})}
{" "}
</Row>
) : (
<></>
)
)}
</Container>
const BlogItem = ({ index, colNum, art, even }) => {
const intl = useIntl();
let wrapperClass;
if (even && index === 0 || !even && index === 2) {
wrapperClass = "col-lg-6";
} else {
wrapperClass = "col-lg-3";
}
return (
<div
className={wrapperClass}
key={index}
>
<Link to={`/blog/${art.slug}`}>
<Card className="card-background">
<div
className="full-background"
style={{
backgroundImage: `url(${process.env.API_URL}${art.featured_image.url})`,
}}
></div>
<Card.Body>
<div className="content-bottom">
<div className="card-category">
{Localization(art.category.name, intl.locale)}
</div>
<Card.Title>{Localization(art.name, intl.locale)}</Card.Title>
</div>
</Card.Body>
</Card>
</Link>
</div>
)
}
Create div elements dynamically within React component
Here is an example how you can dynamically create elements in React:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { count: 3 };
}
render() {
return (
<div>
{[...Array(this.state.count)].map((e, i) => <div key={i}>Row {i}</div>)}
</div>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
How do I add table row dynamically in react?
you can use the useEffect
hook to create an array of dates each time the user changes the duration value. Then you can simply map through this array to display the number of rows required.
This means that you don't need to set the "today" date because it will be setup in this useEffect hook which also runs before the first render.
The final code should look something like this:
import React, { useState, useEffect } from "react";
function App() {
const [loan, setLoan] = useState(1000);
const [duration, setDuration] = useState(1);
const [interest, setInterest] = useState(0);
const [dates, setDates] = useState([]);
const getInterest = () => {
let interestedAmount = (loan * interest) / 100;
interestedAmount /= duration;
return Math.round((interestedAmount + Number.EPSILON) * 100) / 100;
};
const getPrincipal = () => {
let dividedAmount = loan / duration;
return Math.round((dividedAmount + Number.EPSILON) * 100) / 100;
};
const getTotalRepayment = () => {
return getInterest() + getPrincipal();
};
useEffect(() => {
let datesArray = [];
for (let i = 0; i < duration; i++) {
let date = new Date();
date = new Date(date.setMonth(date.getMonth() + i));
datesArray.push(
date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear()
);
}
setDates(datesArray);
}, [duration]);
return (
<React.Fragment>
<header>
<h1>Your Loan</h1>
</header>
<main>
<form>
<div className='row g-3 align-items-center'>
<div className='col-auto'>
<label htmlFor='loan-input' className='form-label'>
Loan Amount (£) : {loan}
</label>
</div>
<div className='col-auto'>
<input
type='range'
value={loan}
min='1000'
max='200000'
step='1000'
className='form-range'
id='loan-input'
onChange={(e) => setLoan(e.target.value)}
/>
</div>
</div>
<div className='row g-3 align-items-center'>
<div className='col-auto'>
<label htmlFor='duration-input' className='form-label'>
Duration (in Months) : {duration}
</label>
</div>
<div className='col-auto'>
<input
type='range'
value={duration}
min='1'
max='60'
step='1'
className='form-range'
id='duration-input'
onChange={(e) => setDuration(e.target.value)}
/>
</div>
</div>
</form>
<div className='row g-3 align-items-center'>
<div className='col-auto'>
<label htmlFor='interest-range' className='form-label'>
Interest Rate (%) : {interest}
</label>
</div>
<div className='col-auto'>
<input
type='range'
value={interest}
min='0'
max='10'
step='1'
className='form-range'
id='interest-range'
onChange={(e) => setInterest(e.target.value)}
/>
</div>
<table className='table'>
<thead>
<tr>
<th scope='col'>Repayment Date</th>
<th scope='col'>Principal</th>
<th scope='col'>Interest</th>
<th scope='col'>Total Repayment</th>
</tr>
</thead>
<tbody>
{dates.map((date, index) => (
<tr key={index}>
<td>{date}</td>
<td>{getPrincipal()}</td>
<td>{getInterest()}</td>
<td>{getTotalRepayment()}</td>
</tr>
))}
</tbody>
</table>
</div>
</main>
</React.Fragment>
);
}
export default App;
Adding dynamic states in reactJs
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>
);
}
}
Add row to existing table dynamically in ReactJS
You are using jquery and directly handling real DOM. With React we use Virtual DOM and don't manipulate the real DOM. Unlike Jquery, in react you don't have to worry about handling UI. Your concern should be handling the data properly, leave the UI updates to React. You haven't provided the Table Component information here. So, I would give you a code sample which does exactly what you want to achieve. For the button you can place it where it's needed within this component.
import React from "react";
class Table extends React.Component {
state = {
data: []
};
appendChild = () => {
let { data } = this.state;
data.push(data.length); // data.length is one more than actual length since array starts from 0.
// Every time you call append row it adds new element to this array.
// You can also add objects here and use that to create row if you want.
this.setState({data});
};
render() {
return (
<table>
<thead>
<th>Type</th>
<th>Position</th>
</thead>
<tbody>
{this.state.data.map(id => (
<Row id = {id} />
))}
</tbody>
</table>
);
}
}
const Row = ({ id }) => (
<tr>
<td>
<input type="text" id={`select-type-${id}`} />
</td>
<td>
<input type="text" id={`select-position-${id}`} />
</td>
</tr>
);
React Dynamically render component within div based on div id
So if you're saying you want to render content dynamically from a list of data? I would look into the map
and filter
functions.
With your example, you could return a set of divs using your array of data. similar to this concept airplaneDataArray.map(data => return <div>...</div>);
The "data" within the mapped array pretty much represents a single piece in the array, so you'd be able to call specific parts of the array using data.arrivals.key
, and so on and so forth. This will generate the divs dynamically without hardcoding a bunch of div rows.
Now if you only want to get arrivals at a specific time, you could use filter to filter out arrivals that don't match the time you want. Honestly not exactly understanding your use case that much so a better example, or something more indepth would be helpful.
Dynamically create Content React
Provided that your api call returns an array of strings this should work.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class Questions extends Component {
state = {
questionValues: null,
};
componentDidMount() {
GetData().then(response => {
if (response) {
if (response.length > 0) {
this.setState({
questionValues: response,
});
}
}
});
}
renderQuestions = () => this.state.questionValues.map(q => <Text key={q}>{q}</Text>);
render() {
if (!this.state.questionValues) return <Text>Here you can return a custom loading component</Text>;
return <View>{this.renderQuestions()}</View>;
}
}
export default Questions;
reactjs render rows dynamically
I'm afraid there's no declarative way to do that - you'll have to slice your projectData.projects
array with Array.slice()
an then for every newly created array output < div className = "row" > /*map the chunk of array like you already do*/</div>
Related Topics
Convert a Flat Json File to Tree Structure in JavaScript
How to I Retrieve Last Part of Url and Use It in HTML
Is There Any Workaround (Or Hack) to Make the Audio Autoplay on Chrome, Firefox and Safari
Calculate the Bounding Box'S X, Y, Height and Width of a Rotated Element Via JavaScript
How to Increment a Number After Every 1 Second Using JavaScript
How to Get Route Url Params in a Page in Nuxt2 and 3
How to Implement Multiple Checkbox Using React Hook
How to Change Image When Two Buttons Are Clicked
How to Pass Input Value into a Function on Form Submit in Angular 6
How to Customize Header Cell in Pdf Using Jspdf-Autotable Plugin
How to Set an Iframe Src Attribute from a Variable in Angularjs
Call Method That Inside Another Component - React Js
React | How to Add Dynamic New Divs Like Rows
Clicking a Button Within a Form Causes Page Refresh
Nested Json: How to Add (Push) New Items to an Object
How to Check If Element Has Focused Child Using JavaScript