passing index through react components - javascript

I'm studying Reactjs and I'm building a tasks project (CRUD) but I'm stuck at the point of editing, the editing part is in another component and I'm not able to send the index of the task that will be edit, I read the documentation but I'm not capable to make it, please if someone can see my code and tell what I'm doing wrong.
the app (main)code
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
// data
import { todos2 } from './todos.json';
// subcomponents
import TodoForm from './components/TodoForm';
import TodoFormEdit from './components/TodoFormEdit';
class App extends Component {
constructor() {
super();
this.state = {
todos2, mode:'view'
}
this.handleAddTodo = this.handleAddTodo.bind(this);
this.handleEdit2 = this.handleEdit2.bind(this);
}
removeTodo(index) {
this.setState({
todos2: this.state.todos2.filter((e, i) => {
return i !== index
})
});
}
handleAddTodo(todo) {
this.setState({
todos2: [...this.state.todos2, todo]
})
}
handleEdit2(i) {
this.setState({mode: 'edit'});
//const mode = mode === 'edit';
alert(i);
/* alert(this.state.todos2[i].title);
alert(this.state.todos2[i].priority);
alert(this.state.todos2[i].description);
alert(this.state.todos2[i].language);*/
}
render() {
const todosAll = this.state.todos2.map((todo, i) => {
return (
<div className="col-md-4" key={i}>
<div className="card mt-4">
<div className="card-title text-center">
<h3>{todo.title} - { i } </h3>
<span className="badge badge-pill badge-danger ml-2">
{todo.priority}
</span>
</div>
<div className="card-body">
<div>
{todo.description}
</div>
<div>
{todo.language}
</div>
</div>
<div className="card-footer">
<button
className="btn btn-danger"
onClick={this.removeTodo.bind(this, i)}>
Delete
</button>
<button
className="btn btn-warning ml-2"
onClick={this.handleEdit2.bind(this, i)}>
Edit
</button>
</div>
</div>
</div>
)
});
return (
<div className="App">
<nav className="navbar navbar-dark bg-dark">
<a className="navbar-brand" href="/">
Tasks
<span className="badge badge-pill badge-light ml-2">
{this.state.todos2.length}
</span>
</a>
</nav>
<div className="container">
<div className="row mt-4">
<div className="col-md-4 text-center">
<img src={logo} className="App-logo" alt="logo" />
{/* <TodoForm onAddTodo={this.handleAddTodo} ></TodoForm> */ }
{this.state.mode === 'view' ? (
<TodoForm onAddTodo={this.handleAddTodo} />
) : (
<TodoFormEdit index={this.state.i}/>
)}
</div>
<div className="col-md-8">
<div className="row">
{todosAll}
</div>
</div>
</div>
</div>
</div>
)
}
}
export default App;
and the Edit component:
import React, { Component } from 'react';
// data
import { todos2 } from '../todos.json';
class TodoFormEdit extends Component {
constructor (i) {
super(i);
this.state = {
todos2
};
}
render() {
return (
<div>
{this.state.todos2[0].title}
</div>
)
}
}
export default TodoFormEdit;

You're passing this.state.i:
<TodoFormEdit index={this.state.i}/>
It's not clear where you set it–I see mode and todos2 state properties, I don't see i anywhere.

Related

I have made a card and I want to loop the whole card component

I have made 1 card component. Here I want to loop through it, So that I can Use it again and again.
/* CardUI.jsx*/
import React from "react";
import img1 from "../assets/raj.jpg";
import "./Cards.css";
import { FaTshirt, FaLocationArrow } from "react-icons/fa";
import { BsGeoAlt } from "react-icons/bs";
import { GiTakeMyMoney } from "react-icons/gi";
import { MdEventAvailable } from "react-icons/md";
import { IoLogoDesignernews } from "react-icons/io5";
let skills=["Python","mongos","Java"]
/Here I want to loop through Card, so that I can make several card. How Can I achieve that. I Want to achieve loop, so that I do not have to re render card again and again. Here card is the functional component./
const Card= (props) => {
return (
<div className="card container">
<div className="card-body row">
<img src={img1} style={{marginRight:"10px",paddingRight:"10px"}} className="image col-sm-2" alt="raj" />
<div className="col-md-6" style={{textAlign:"left",marginLeft:"-5px",marginRight:"10px",paddingRight:"80px",paddingLeft:"0px"}}>
<h5 style={{ font: "1px",marginBottom:"0px"}}>{props.name}</h5>
<p style={{ font: "0px",marginTop:"0px"}}><MdEventAvailable/> {props.current_availability}</p>
</div>
<h5 className="Rating col-sm-2">9.5</h5>
</div>
<div id="box" className="row box-aligner" style={{marginTop:"-20px"}}>
<div>
<div className="row" style={{marginLeft:"100px"}}>
{
skills.map((skill)=>(
<div className="col-sm-2" style={{ marginRight:"15px",marginLeft:"0px"}}>
<p className="language row-aligner">{skill}</p>
</div>
))
}
</div>
</div>
<div style={{marginRight:"5px",fontSize:"15px", paddingRight:"30px"}}>
< BsGeoAlt/> New Delhi - 9.6km
</div>
</div>
<div id="designation" className="row" style={{marginTop:"-10px"}}>
<div className="col-md-6">
<h1 className="row-aligner" style={{marginRight:"20px",paddingLeft:"25px",marginLeft:"51px"}}>
<FaTshirt/> 4years,2months
</h1>
</div>
<div className="col-sm-6">
<h2 className="city" style={{paddingLeft:"65px", paddingRight:"20px", fontWeight:"normal",marginLeft:"15px"}}><IoLogoDesignernews/> {' '} Interaction Designer</h2>
</div>
</div>
<div id="salary" className="row" style={{marginTop:"-4px"}}>
<div className="col-md-6" >
<h1 className="row-aligner" style={{marginRight:"-4px", paddingLeft:"25px", marginLeft:"10px"}}><GiTakeMyMoney/> $10k-25k/ mo</h1>
</div>
<div className="col-md-6">
<a href="#" class="btn btn-primary">
Hire Now
</a>
</div>
</div>
</div>
);
};
export default Card;
/Card.jsx/
/*Here is the Parent file. Class component has been used here.*/
import React,{Component} from 'react'
import Card from './CardUI'
class Cards extends Component{
render(){
return(
<div className="container-fluid d-flex justify-content-center" style={{marginTop:"100px"}}>
<div className="row">
<div className="col-md-12">
<Card name={"Sara"}
current_availability={"Available"}
workExperience={"4"}
Location={"delhi"}
distance={"9.6 km"}
JobTitle={"Designer"}
/>
</div>
</div>
</div>
)
}
}
export default Cards;

Error arising in my code. I am using React, NPM and styled components. What are the steps I need to take?

import React, { Component } from "react";
import Product from "./Product";
import Title from "./Title";
import { ProductConsumer } from "../context";
export default class Productlist extends Component {
render() {
return (
<React.Fragment>
<div className="py-5">
<div className="container">
<Title name="our" title="products" />
<div className="row">
<ProductConsumer>
{value => {
return value.products.map(product => {
return <Product key={product.id} product={product} />;
});
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
);
}
}
Okay, I am getting this error and I am not quite sure what it is since I am so new to working with React.JS. could someone assist me in figuring out what may be happening.
export default class Product extends Component {
render() {
const { id, title, img, price, inCart } = this.props.product;
return (
<ProductWrapper className="col-9 mx-auto col-md-6 col-lg-3 my-3">
<div className="card">
<div
className="img-container p-5"
onClick={console.log("you clicked me on the image container")}
>
<Link to="/details">
<img src={img} alt="product" className="card-img-top" />
</Link>
</div>
</div>
</ProductWrapper>
);
}
}
const ProductWrapper = styled.div
Above is the Product code as asked! Thank you!

How to access a function from another component that is located in another js file by clicking a button in create-react-app?

I have two files index.js and map.js. In map.js I have Kartta component, that contains a leaflet map and a method fetchAll() that creates markers on the map from the coordinates that it gets from API, which in this case is test.json. It works fine if I put the method inside componentDidMount(), it creates the markers on load. However I want to create those markers by clicking the button "Haku", which is located inside Sidebar component in index.js.
Here is map.js
import React, { Component } from 'react';
import L from 'leaflet';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import { fetchAll } from './search';
const position = [62.241581, 25.758742];
class Kartta extends Component {
state = {
kohteet: []
}
componentDidMount() {
this.fetchAll();
}
fetchAll = () => {
console.log("täällä");
fetch('test.json')
.then(res => res.json())
.then((data) => {
this.setState({ kohteet: data })
})
.catch(console.log(this.state.kohteet))
}
iconSize = (iconName) => {
if (iconName == 'tree.png') {
return 30, 30
}
else {
return 15, 30
}
}
render() {
return (
<div id="mapid" className="h-100 w-100">
<Map center={position} zoom={7}>
<button onClick={this.haeKaikki}>Hae</button>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution="© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
/>
{this.state.kohteet.map((kohde) => (
<Marker key={'key' + kohde.id} position={[kohde.lon, kohde.lat]} icon={
new L.Icon({
iconUrl: require('../img/' + kohde.icon),
iconSize: new L.Point(this.iconSize(kohde.icon)),
id: kohde.id + kohde.icon
})
}>
<Popup>
<h1>{kohde.name}</h1>
<p>{kohde.desc}</p>
</Popup>
</Marker>
))}
</Map>
</div>
)
}
}
export default Kartta
Here is index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './css/main.css';
import 'bootstrap/dist/js/bootstrap.bundle.js';
import 'leaflet/dist/leaflet.css';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faSearch, faInfoCircle } from '#fortawesome/free-solid-svg-icons';
import Kartta from './components/map';
// Yläpalkki
class Navbar extends React.Component {
render() {
return (
<nav id="nav-bar" className="navbar navbar-expand-lg navbar-dark bg-primary">
<a id="nav-bar-a0" className="navbar-brand" href="/">MeijänMetsät</a>
<button id="toggle-search-btn" type="button" href="#sidebar" data-toggle="collapse" className="btn btn-primary">
<FontAwesomeIcon icon={faSearch} />
<span> Haku</span>
</button>
<ul id="nav-bar-ul0" className="navbar-nav mr-auto">
</ul>
<div id="nav-bar-div0" className="dropdown">
<button id="nav-bar-button0" className="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Kirjaudu
<span id="nav-bar-span0" className="caret"></span></button>
<div id="dropdown-div0" className="p-2 dropdown-menu dropdown-menu-right" style={{"minWidth":"350px"}}>
<form id="dropdown-form0">
<div id="dropdown-div1" className="form-group">
<label id="dropdown-label0" htmlFor="exampleInputEmail1">Sähköposti</label>
<input id="dropdown-input0" type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Syötä sähköposti" />
</div>
<div id="dropdown-div2" className="form-group">
<label id="dropdown-label1" htmlFor="exampleInputPassword1">Salasana</label>
<input id="dropdown-input1" type="password" className="form-control" id="exampleInputPassword1" placeholder="Salasana" />
</div>
<div id="dropdown-div3" className="row">
<button id="dropdown-button0" type="submit" className="ml-3 btn btn-primary">Kirjaudu</button>
<button id="dropdown-button2" type="submit" className="ml-2 btn btn-primary">Rekiströidy</button>
<button id="dropdown-button1" type="submit" className="ml-2 btn btn-secondary">Facebook</button>
</div>
</form>
</div>
</div>
</nav>
);
}
}
// Sivupalkki
class Sidebar extends React.Component {
render() {
return (
<div className="p-2 collapse in" id="sidebar">
<div className="list-group panel" id="sidebar-div0">
<form id="sidebar-form0">
<div id="sidebar-div01" className="form-group active">
<label id="sidebar-label0" htmlFor="exampleInputEmail1">Kohteen nimi</label><span> </span>
<FontAwesomeIcon icon={faInfoCircle} className="pointer dropdown-toggle" data-toggle="dropdown" alt="Hakuohjeet" />
<div id="search-info" className="p-2 dropdown-menu dropdown-menu-right">
<p>Hae kirjoittamalla tägejä</p>
</div>
<div className="row">
<div className="col-7 ml-3 p-0">
<input type="text" className="form-control" id="searchByName" aria-describedby="emailHelp" placeholder="Syötä kohteen nimi" />
</div>
<button id="sidebar-button0" type="submit" className="btn btn-primary ml-2 col-3" onClick={() => Kartta.fetchAll}>Haku</button>
</div>
</div>
</form>
<div id="sidebar-div02" className="dropdown">
<a id="sidebar-button1" className="btn btn-light dropdown-toggle p-0 thaku" type="button" data-toggle="dropdown">Tarkennettu haku
<span id="sidebar-span0" className="caret"></span></a>
<div id="sidebar-div020" className="p-0 dropdown-menu border-0 mt-2 w-100 h-100">
<form id="sidebar-form1">
<div id="sidebar-div0200" className="form-group p-0">
<label id="sidebar-label1" htmlFor="exampleInputEmail1">Paikkakunta</label>
<input id="sidebar-input1" type="text" className="form-control" placeholder="Syötä paikkakunta" />
</div>
<div id="ch-div0" className="row pl-3">
<label id="lbl-location">Sijainti</label>
<input id="ch-location" className="mt-2 ml-2" type="checkbox" aria-label="Checkbox for following text input" />
</div>
<div className="input-group mb-3">
<div className="input-group-prepend">
<label className="input-group-text" htmlFor="inputGroupSelect01">Palvelut</label>
</div>
<select className="custom-select" id="inputGroupSelect01">
<option defaultValue>Valitse...</option>
<option value="1">Kakkapaikka</option>
<option value="2">Pissapaikka</option>
<option value="3">Kaljapaikka</option>
</select>
</div>
<div id="dropdown-div3" className="row p-0">
<button id="dropdown-button0" type="submit" className="ml-3 btn btn-primary">Tarkennettu haku</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
// Sisältö
class Content extends React.Component {
render() {
return (
<div id="main-container" className="container-fluid h-100 p-0">
<Navbar />
<div id="container0" className="row h-100 w-100 m-0 wrapper">
<Sidebar />
<div id="container02" className="col h-100 w-100 p-0">
<Kartta />
</div>
</div>
</div>
);
}
}
ReactDOM.render(<Content />, document.getElementById('root'));
The button "Haku" has onClick={() => Kartta.fetchAll}, but it does not do anything, it isn't even accessing the fetchAll() function. The function works perfectly if I create the button on the map, but I don't want to do that, the button has to be on the Sidebar as the plan is to use a search word in the future.
Thank you!
you need to create a prop e.g. createmap:booleanin Kartta component. Now in index.js firstly you need to create a state e.g. createmap:boolean (initially set to false) and upon Haku button click you need to set the state:
this.setState({
creatmap:true;
});
you need to include Katta component JSX in index.js render() function e.g.
<Kartta createmap = {this.state.createmap} />
Now in Kartta component on componentDidMount()you can check createmap' prop and based on its value call the functionfetchAll()`:
public componentDidMount() {
if(this.prop.createmap) {
fetchAll();
}
}
what this will do is causing rerendering due to setting state upon button click and will call 'fetchAll()' function if createMap is found true
Hope this helps.
EDIT:
Don't forget to use export keyword with your Kartta component class so you can import it in index.js to create its JSX in render():
export default class Kartta extends Component { ... }
EDIT 2
In your navbar component class initialize state in constructor:
export default class NavBar extends Component {
constructor(props) {
super(props);
this.state: {
createmap: false;
}
}
}
your Kartta component class:
export default class Kartta extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
if(this.props.createmap) {
fetchAll();
}
}

How can I display array of data in specific div id by click in a button?

I create a component of react. and there one array with some values. so I need to display that value or data in any specific div by clicking in a button.
this is my array in component.
constructor(){
super()
this.state = {
notificaion: [
"Notification-1",
"Notification-3",
"Notification-4",
"Notification-5",
]
}
}
this is my button with click event.
<button onClick={this.getNotification}>{this.state.notificaion.length}</button>
this is the function that I have create. and to push data in specific div.
getNotification = () =>{
return(
this.state.notificaion.map(items =>(
<li key={items}>{items}</li>
))
)
}
here I want to display when buttons is clicked
<strong>{this.getNotification()}</strong>
This is my full code that I have been tried.
import React, {Component} from 'react';
class Menu2 extends Component{
constructor(){
super()
this.state = {
notificaion: [
"Notification-1",
"Notification-3",
"Notification-4",
"Notification-5",
]
}
}
getNotification = () =>{
return(
this.state.notificaion.map(items =>(
<li key={items}>{items}</li>
))
)
}
render(){
return(
<div className="header">
<div className="container">
<div className="row">
<div className="col-lg-12 col-sm-12 col-xs-12">
<div className="text-center mb-20">
<h1>Notificaion Status</h1>
<p>Check notificatin read/unread</p>
</div>
</div>
</div>
<div className="row">
<div className="col-lg-12 col-sm-12 col-xs-12">
<div className="card border-dark mb-3">
<div className="card-body text-dark">
<p className="card-text" style={{textAlign: 'center'}}>
{this.state.notificaion.length > 0
?
<span>You Have <button onClick={this.getNotification}>{this.state.notificaion.length}</button> Unread Notifications</span>
:
<span>You Have <button onClick={this.getNotification}>{this.state.notificaion.length}</button> Unread Notifications}</span>}
</p>
<strong>{this.getNotification()}</strong>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Menu2;
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
notificaion: [
"Notification-1",
"Notification-3",
"Notification-4",
"Notification-5",
],
notificationHtml: ""
}
}
getNotification = () => {
this.setState({
notificationHtml: this.state.notificaion.map(items => (
<li key={items}>{items}</li>
))
});
}
render() {
return (
<div className="App">
<button onClick={this.getNotification}>{this.state.notificaion.length}</button>
<div>
{this.state.notificationHtml}
</div>
</div>
);
}
}
export default App;
I would implemented as such:
this.state = {
visible: false,
notifications: ...
}
toggleVisibility() =>{
this.setState({
visibile: true
})
}
Don't forget to bind the "toggleVisibility" function. Then
in your component:
<button onClick={this.toggleVisibility}/>
...
{if(this.state.visible){
<strong>this.state.notifications.map(notification,i) =>
<li key={i}>{notification}</li>
</strong>
}
You can add a property showNotification in state. And based on the value of it, we can show the notification.
Also add a method showNotificationHandler that toggles the showNotification value.
class Menu2 extends Component {
constructor() {
super();
this.state = {
notificaion: [
"Notification-1",
"Notification-3",
"Notification-4",
"Notification-5"
],
// adding a property "showNotification"
showNotification: false
};
}
getNotification = () => {
return this.state.notificaion.map(items => <li key={items}>{items}</li>);
};
// method that toggles the "showNotification" value
showNotificationHandler = () => {
this.setState(({ showNotification }) => ({
showNotification: !showNotification
}));
};
render() {
return (
<div className="header">
<div className="container">
<div className="row">
<div className="col-lg-12 col-sm-12 col-xs-12">
<div className="text-center mb-20">
<h1>Notificaion Status</h1>
<p>Check notificatin read/unread</p>
</div>
</div>
</div>
<div className="row">
<div className="col-lg-12 col-sm-12 col-xs-12">
<div className="card border-dark mb-3">
<div className="card-body text-dark">
<p className="card-text" style={{ textAlign: "center" }}>
{this.state.notificaion.length > 0 ? (
<span>
You Have{" "}
<button onClick={this.showNotificationHandler}>
{this.state.notificaion.length}
</button>{" "}
Unread Notifications
</span>
) : (
<span>
You Have{" "}
<button onClick={this.showNotificationHandler}>
{this.state.notificaion.length}
</button>{" "}
Unread Notifications}
</span>
)}
</p>
<strong>
// Depending on the value of "showNotification" we get notification
// if "showNotification" is true then get the notification
{this.state.showNotification && this.getNotification()}
</strong>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Menu2;

Cannot render correctly using conditionals in React

is there a correct manner to render in React using conditionals that I haven't figured out? I've spent some time with this and can't get why it only renders the 'Standard' .
Each one of the Standard, Filled, Premium components are simple rendering some HTML...
Here's what I've coded.
import React, { Component } from "react";
import { PropTypes } from "prop-types";
import { connect } from "react-redux";
import Standard from "./Standard";
import Filled from "./Filled";
import Premium from "./Premium";
class Plans extends Component {
constructor(props) {
super(props);
this.state = {
selectedplan: ""
};
this.onClick = this.onClick.bind(this);
}
onClick = e => this.setState({ selectedplan: e.target.name });
componentDidMount() {
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
render() {
var plan = this.state.selectedplan;
let content;
if (plan === "standard") {
content = <Standard />;
} else if (plan === "filled") {
content = "Testing... worked.?";
} else if (plan === "premium") {
content = <Premium />;
} else {
content = (
<div className="lead text-center">Select a plan to view more</div>
);
}
return (
<div>
<div className="row">
<div
className="col-sm-4 card card-info text-center justify-content-center"
style={{ margin: "auto" }}
>
<h3 onClick={this.onClick} name="standard">
Standard
</h3>
<ul>
<li />
</ul>
</div>
<div
className="col-sm-4 card text-center justify-content-center"
style={{ margin: "auto" }}
>
<h3 name="filled" onClick={this.onClick}>
Feature-Filled
</h3>
<ul>
<li />
</ul>
</div>
<div
className="col-sm-4 card card-info text-center justify-content-center"
style={{ margin: "auto" }}
>
<h3 name="premium" onClick={this.onClick}>
Super Premium
</h3>
<ul>
<li />
</ul>
</div>
</div>
<hr />
<div className="container text-center justify-content-center">
{content}
</div>
</div>
);
}
}
Plans.propTypes = {
auth: PropTypes.object.isRequired,
onClick: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(Plans);
Thanks in advance!!
Maybe this will point you in the right direction.
class Plans extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedplan: ""
};
}
render() {
let { selectedplan } = this.state,
content;
if (selectedplan === "standard") {
content = <div>Standard</div>;
} else if (selectedplan === "filled") {
content = <div>Filled</div>;
} else if (selectedplan === "premium") {
content = <div>Premium</div>;
} else {
content = (
<div className="lead text-center">Select an option to view more</div>
);
}
return (
<div>
<div className="row">
<div
className="col-sm-4 card card-info text-center justify-content-center"
style={{ margin: "auto" }}
>
<h3
onClick={() => this.setState({ selectedplan: "standard" })}
name="standard"
>
Standard
</h3>
<ul>
<li />
</ul>
</div>
<div
className="col-sm-4 card text-center justify-content-center"
style={{ margin: "auto" }}
>
<h3
name="filled"
onClick={() => this.setState({ selectedplan: "filled" })}
>
Feature-Filled
</h3>
<ul>
<li />
</ul>
</div>
<div
className="col-sm-4 card card-info text-center justify-content-center"
style={{ margin: "auto" }}
>
<h3
name="premium"
onClick={() => this.setState({ selectedplan: "premium" })}
>
Super Premium
</h3>
<ul>
<li />
</ul>
</div>
</div>
<hr />
<div className="container text-center justify-content-center">
{content}
</div>
</div>
);
}
}
ReactDOM.render(<Plans />, 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>
<body>
<div id='root'></div>
</body>

Categories

Resources