When I clicked a link it renders a view based on the "id" from a JSON. I need to apply a background color when a certain view renders. And I should toggle the Style.
This code shows the crawl when I clicked a particular link.
handleCrawl = e => {
const { id } = e.target;
this.setState(current => ({
showCrawl: { [id]: !current.showCrawl[id] }
}));
};
This is my render method where Ia am mapping the links and the additional details on JSON
render() {
return (
<div class="d-flex" id="wrapper">
<div class="bg-light border-right" id="sidebar-wrapper">
<h1 class="sidebar-heading">API</h1>
<ul class="list-group list-group-flush">
{this.state.apis.map(api => (
<li><a class="list-group-item list-group-item-action bg-light" key={api.id}
id={api.id}
onClick={this.handleCrawl}>{api.title}</a></li>
))}
</ul>
</div>
<div id="page-content-wrapper">
<div class="container-fluid">
{this.state.apis.map(api => (
<div
key={api.id}
id={api.id}>
{this.state.showCrawl[api.id] && (
<SwaggerUI url={api.opening_crawl}/>
)}
</div>
))}
</div>
</div>
</div>
);
}
Not sure if it answers your question.
You can toggle the style conditionally.
{this.state.apis.map(api => (
<div
key={api.id}
id={api.id}
className={this.state.showCrawl[api.id]?"some-specific-style":"default-or-empty"}
>
{this.state.showCrawl[api.id] && (
<SwaggerUI url={api.opening_crawl}/>
)}
</div>
))}
Related
I am mapping data inside a div, all i need a border to div of "lab_add_to_cart_samp1" classname after clicking that division. I am confused how to make a division show active onclick even after mapping the data, there is an array of allabtest from API call
<div className="lab_add_to_cart_samp">
{
allabtest.map((item, index) => {
return <div className="lab_add_to_cart_samp1" key={index}>
<div className="lab_add_to_cart_samp_img1">
<img src={REACT_APP_BASE_URL+"lab-test/download/"+item.id} />
</div>
<div className="lab_add_to_cart_test_desc">
<p id="labtest_desc_txt1">{item.name}</p>
<p id="labtest_desc_txt2">What it include :</p>
<div className="labtest_desc1">
<div className="labtest_desc_detail">
<ul>
<li>Platate</li>
<li>CBC</li>
<li>HB</li>
</ul>
</div>
<div>
<ul id="lab_test_detail">
<li>PCV</li>
<li>WBC/TLC</li>
<li>WBC/TLC</li>
</ul>
</div>
<div>
<ul id="lab_test_detail">
<li>DLC</li>
<li>RBC</li>
<li>ESR</li>
</ul>
</div>
<div>
<ul id="lab_test_detail">
<li>Platelets</li>
<li>Reticilocytes</li>
<li>Blood Grouping Rh type</li>
</ul>
</div>
</div>
</div>
<div className="lab_add_to_cart_price">
<p>Rs. {item.price}</p>
<div className="lab_add_to_cart_atc">
<button onClick={()=>addtocart(item)}>
<p>Add to Cart</p>
</button>
</div>
</div>
</div>
})
}
</div>
If you want to set active for multiple divs at the same time you can do it like this
const allabtest = [
{id: 'one', name: 'one'},
{id: 'two', name: 'two'},
{id: 'three', name: 'three'},
]
function App() {
const [activeCart, setActiveCart] = useState({});
return (
<div className="lab_add_to_cart_samp">
{allabtest.map((item, index) => {
return (
<div
className={
activeCart[item.id] === true
? "lab_add_to_cart_samp1 active"
: "lab_add_to_cart_samp1"
}
onClick={() =>
setActiveCart({
...activeCart,
[item.id]: !Boolean(activeCart[item.id])
})
}
key={item.id}
>
<div>{item.name}</div>
</div>
);
})}
</div>
);
}
If you want to track only one div then
function App() {
const [activeCart, setActiveCart] = useState();
return (
<div className="lab_add_to_cart_samp">
{allabtest.map((item, index) => {
return (
<div
className={
activeCart === item.id
? "lab_add_to_cart_samp1 active"
: "lab_add_to_cart_samp1"
}
onClick={() => setActiveCart(item.id)}
key={item.id}
>
{/* Rest of your stuffs */}
</div>
);
})}
</div>
);
}
I am working on a header component. Here is the code:
import style from '../../styles/header.css';
import '../../styles/globals.css';
export default function Header({data}){
const [showMe, setShowMe] = useState(false);
function toggle(){
console.log("toggle")
setShowMe(!showMe);
}
return(
<>
<div className="header">
<div className="web-header">
<div className="first-header">
<div className="info-strip">
<ul>
<li>
Contact Us
</li>
<li>
7 Day Returns
</li>
<li>
Track Order
</li>
<li>
Return Order
</li>
<li>
Survey
</li>
</ul>
</div>
<div className="right-block d-flex">
<div className="login">
<span className="image"></span>
<span className="text">Log In
<div className="account-box">
</div>
</span>
</div>
<div className="cart">
<span className="cart-image">
</span>
<span className="text">Cart</span>
</div>
</div>
</div>
<div className="second-header">
<div className="header-logo">
<img src="https://www.mirraw.com/assets/logo-red.png" />
</div>
<div className="search">
<input placeholder="Search Something.." />
<button></button>
</div>
</div>
<div className="third-header">
<div className="container-fluid">
<ul className="menu">
{data.menus.map((post, index) => {
return (
<li className="menu-list">
{post.title}
<div className="megabox">
<ul className="wrapper">
{post.menu_columns.map((subItems, sIndex) => {
return <li>
<span className="menu-link">
{subItems.title}
</span>
<ul className="category">
{subItems.menu_items.map((x) => {
return <li>
{x.title}
</li>
})}
</ul>
</li>;
})}
</ul>
</div>
</li>)})}
</ul>
</div>
</div>
</div>
<div className="mobile-screen">
<div className="mobile-header">
<div className="mobile-menu">
<div className="menu-icon">
<div className="wrapper">
<input type="checkbox" id="navigation" />
<label for="navigation">
+
</label>
<div className="right-card">
<img src="https://www.mirraw.com/assets/logo-red.png" />
<p className="app-install">
<span>Download app</span>
</p>
<div className="cart">
<span className="cart-image"></span>
{/* <span className="text">Cart</span> */}
</div>
</div>
<nav>
<ul>
<li className="menu-heading">
<span>Menu</span>
<span>
<label for="navigation">X</label>
</span>
</li>
{data.menus.map((post, index) => {
return (
<li className="menu-list">
{post.title} <span onClick={toggle}>+</span>
<ul style={{display: showMe?"block":"none"}} className="category-one">
{post.menu_columns.map((subItems, sIndex) => {
return <li>
{subItems.title}
<span>+</span>
<ul className="category-two">
{subItems.menu_items.map((x) => {
return <li>
{x.title}
</li>
})}
</ul>
</li>;
})}
</ul>
</li>)})}
</ul>
</nav>
</div>
</div>
</div>
<div className="scroll-menu-list">
<ul className="mb-0">
{data.menus.map((post, index) => {
return (
<li className="menu-list">{post.title}</li>
)})}
</ul>
</div>
</div>
</div>
</div>
</>
)
}
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://api.mirraw.com/api/v1/menu`);
const data = await res.json();
// Pass data to the page via props
return { props: { data } }
}
Code is working fine if I render this page only, but when I import this component in other component, it threw error:
Server Error
TypeError: Cannot read property 'menus' of undefined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
What could be the approach of getting value from the API for child component?
getServerSideProps can only be used within page components, which is why it works when you render this component as a page.
If you want to this to be a reusable component that can be called from other components and/or pages you'll need to pass the data you get at the page level (from getServerSideProps, for instance) down to it.
// pages/index.js
import Header from "../components/header"
export default function IndexPage({ data }) {
return (
<Header data={data} />
)
}
export async function getServerSideProps() {
const res = await fetch(`https://api.mirraw.com/api/v1/menu`);
const data = await res.json();
return { props: { data } }
}
class Navbar extends Component {
state = {};
getLink = (e) => {
const select = document.getElementById("drpdwn");
console.log(select.value);
};
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<div
id="drpdwn"
onClick={() => this.getLink()}
className="dropdown"
>
<span className="dropbtn">Dropdown</span>
<div className="dropdown-content">
<a value="link1" href="#">
Link 1
</a>
<a value="link2" href="#">
Link 2
</a>
<a value="link3" href="#">
Link 3
</a>
</div>
</div>
</nav>
</div>
</>
);
}
}
export default Navbar;
All I want is whenever a user selects any link such as Link 1,2 or 3 I just want to get the value as simple as that. but all I'm getting is undefined. any suggestions??
You can change the code like this and use tags instead of and then tags.
import React, { Component } from "react";
class Navbar extends Component {
state = {};
getLink = (e) => {
const changeValue = e.target.value
console.log(changeValue )
};
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<select
id="drpdwn"
onChange={(e) => this.getLink(e)}
className="dropdown"
>
<option value="link1" href="#">
Link 1
</option>
<option value="link2" href="#">
Link 2
</option>
<option value="link3" href="#">
Link 3
</option>
</select>
</nav>
</div>
</>
);
}
}
export default Navbar;
First, remove the anonymous function inside your onClick, like this :
onClick={this.getLink}
This will automatically pass the event into your function, so (e) will be defined. This is the equivalent of doing :
onClick={(e) => this.getLink(e)}
Once you've done that, you must recover the value inside the event in your function.
getLink = (e) => {
const value = e.target.value;
console.log(value);
};
I notice you want to create a navbar with a dropdown list
class Navbar extends Component {
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<div
id="drpdwn"
onClickCapture={(e) => {
e.preventDefault();
// e.target which is the target you click within this div
console.log(e.target);
}}
className="dropdown"
>
<span className="dropbtn">Dropdown</span>
<div className="dropdown-content">
<a href="/">
Link 1
</a>
<a href="/">
Link 2
</a>
<a href="/">
Link 3
</a>
</div>
</div>
</nav>
</div>
</>
);
}
}
This is how you can do it.
import React, { Component } from "react";
class Navbar extends Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
getLink = ({ target }) => {
if (target.tagName.toLowerCase() === "a") {
console.log(target.getAttribute("value"));
}
};
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<div id="drpdwn" onClick={this.getLink} className="dropdown">
<span className="dropbtn">Dropdown</span>
<div className="dropdown-content">
<a value="link1" href="#">
Link 1
</a>
<a value="link2" href="#">
Link 2
</a>
<a value="link3" href="#">
Link 3
</a>
</div>
</div>
</nav>
</div>
</>
);
}
}
export default Navbar;
You may try the demo in codesandbox
https://codesandbox.io/s/gettingthevalue-yeqoi
I am trying to pass data from child to parent state using
I have to state ProjectList and Header, the header(website header) state is the child compenent of parent, there links on header,if it clicks the link then I am getting an id through that link and then passing that id to through redirect.
but it gives me error maximum dept exceeded.The id I want to passs from header to project list is also coming from other state which is not the child of project list.
ProjectList State:
class ProjectList extends React.Component{
constructor(props){
super(props);
this.showDetail=this.showDetail.bind(this);
this.state={
category_projects:[],
projectPage:false,
clk_project:null,
category:[]
}
}
componentDidMount() {
fetch(`http://127.0.0.1:8000/portfolio/get_category_project/`+this.props.match.params.id+'/').then(response => response.json())
.then(projectsJson => this.setState({category_projects: projectsJson},()=>{
this.sortProjects()
}))
fetch('http://127.0.0.1:8000/portfolio/create_category/')
.then(response=>response.json())
.then(categoryJson => this.setState({category: categoryJson},()=>{
this.sortCategory()
}))
}
sortCategory = ()=>{
let sortArray=this.state.category;
let swap;
for (let i=0;i<sortArray.length;i++)
{
for (let j=0;j<sortArray.length;j++){
if(sortArray[i].category_rank>sortArray[j].category_rank){
swap=sortArray[i];
sortArray[i]= sortArray[j];
sortArray[j]=swap;
}
}
}
this.setState({category:sortArray})
};
showDetail=(evt)=>{
evt.preventDefault();
this.setState({projectPage:true});
this.setState({clk_project:JSON.parse(evt.currentTarget.getAttribute('data-item'))});
};
sortProjects=()=>{
let sortArray=this.state.category_projects;
let swap;
for (let i=0;i<sortArray.length;i++)
{
for (let j=0;j<sortArray.length;j++){
if(sortArray[i].project_rank>sortArray[j].project_rank){
swap=sortArray[i];
sortArray[i]= sortArray[j];
sortArray[j]=swap;
}
}
}
this.setState({category_projects:sortArray})
};
render() {
let redirect=null;
if (this.state.projectPage){
redirect=<Redirect to={`/project/${this.state.clk_project.id}`}/>
}
return(
<div>
{redirect}
<div className="site_wrapper">
<div className="clearfix">
</div>
<Header category={this.state.category}/>
<div className="clearfix">
</div>
<div className="page_title2">
<div className="container">
<div className="title"><h2>Projects</h2></div>
</div>
</div>
<div className="clearfix">
</div>
<div className="container">
<br />
{this.state.category_projects.map(proj=>{
return(
<div className="column">
<img data-item={JSON.stringify(proj)} onClick={this.showDetail} src={"http://127.0.0.1:8000"+proj.file} alt="Snow" className="ImgWidth"/>
</div>
)
})}
</div>
<div className="clearfix margin_top5">
</div>
<div className="footer_graph">
</div>
<Footer projects={this.state.category_projects} id={this.props.match.params.id}/>
</div>
</div>
)
}
}
Header State:
class Header extends React.Component{
constructor(props){
super(props);
this.showCatDetail=this.showCatDetail.bind(this);
this.state={
category:[],
clk_category:[],
detail:false
}
}
showCatDetail=(e)=>{
e.preventDefault();
this.setState({detail:true,clk_category:JSON.parse(e.currentTarget.getAttribute('data-item'))},()=>{
console.log(this.state.clk_category)
});
};
render(){
let hreflink=null;
let redirect=null;
if (this.state.detail){
redirect=<Redirect to={`/category_project/${this.state.clk_category.id}`}/>
}
return(
<div>
{redirect}
<header id="header">
<div id="trueHeader">
<div className="wrapper">
<div className="container">
<div className="logo">
<a href={hreflink} id="logo">
</a>
</div>
<div className="menu_main">
<div className="navbar yamm navbar-default">
<div className="container">
<div className="navbar-header">
<div className="visibledevice">
<ul className="nav navbar-nav">
<li><a href={hreflink} className="active">
<i className="fa fa-home">
</i> Home</a></li>
</ul>
</div>
</div>
<div className="navbar-collapse collapse pull-right">
<ul className="nav navbar-nav">
<li><a href={hreflink} className="active">
<i className="fa fa-home">
</i> Contact Us</a></li>
{this.props.category.map(cat=>{
return(
<li data-item={JSON.stringify(cat)} onClick={(e)=>this.showCatDetail(e)}><a href={hreflink} >
<i className="fa fa-home">
</i>{cat.category_name}</a></li>
)
})}
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
</div>
)
}
}
this.props.match.params.id this id I want to get from header as I trying to pass from in header.The this.props.match.params.id in project list can come from Header or other state.Please need suggestion how to pass this id from header to project list as well as the id can comes from other state to project.
I have a child component that sees all the props but one array that I am trying to map over.
react dev tool sees the array:
but I get "Cannot read property 'map' of undefined"
class Header extends Component {
render() {
const nav = this.props.data.nav.map(i => `<li>${i}</li>`)
return (
<div className="header">
<div className="left">
<h1>{this.props.data.name}</h1>
<p>{this.props.data.tag}</p>
</div>
<div className="right">
<h2>{this.props.data.t1}</h2>
<h3>{this.props.data.t2}</h3>
</div>
<div className="header-contact">
<a rel="noopener" href="tel:+14156943568">
<FontAwesomeIcon icon={faPhone} /> {this.props.data.phone}
</a>
<a rel="noopener" href="mailto:tim.smith.hdg#gmail.com">
<FontAwesomeIcon icon="at" /> {this.props.data.email}
</a>
</div>
<nav id="nav" className='nav'>
<ul>
{
//nav
}
</ul>
</nav>
</div>
);
}
}
I'm using the <Header /> component in the follow way:
class Resume extends Component {
constructor(props) {
super();
this.state = { header: {}, skills: {} }
}
componentDidMount() {
this.setState({
...data
});
}
render() {
return (
<div className="resume">
<Header data={this.state.header} />
<Skills data={this.state.skills} />
</div>
);
}
}
You should check that props.data is defined, and that props.data.nav is an array, to address the errors.
The reason you need to perform this check is because the props.data.nav is not present during the first render() of the <Header /> component. This is because the nav data is only available after the componentDidMount() hook in <Resume /> is called (which happens after the first render of <Header />)
You could make the following adjustment to resolve this:
class Header extends Component {
// [UPDATE] add helper method to simplify safer access to data.nav array
getNavItems() {
// If no data, return empty array
if(!this.props.data) return [];
// If nav not an array, return empty array
if(!Array.isArray(this.props.data.nav)) revturn [];
// Safely access/return nav array
return this.props.data.nav;
}
render() {
// [UPDATE] use local helper getNavItems method to safely access item array
const nav = this.getNavItems().map(i => `<li>${i}</li>`)
return (
<div className="header">
<div className="left">
<h1>{this.props.data.name}</h1>
<p>{this.props.data.tag}</p>
</div>
<div className="right">
<h2>{this.props.data.t1}</h2>
<h3>{this.props.data.t2}</h3>
</div>
<div className="header-contact">
<a rel="noopener" href="tel:+14156943568">
<FontAwesomeIcon icon={faPhone} /> {this.props.data.phone}
</a>
<a rel="noopener" href="mailto:tim.smith.hdg#gmail.com">
<FontAwesomeIcon icon="at" /> {this.props.data.email}
</a>
</div>
<nav id="nav" className='nav'>
<ul>
{
//nav
}
</ul>
</nav>
</div>
);
}
}
Can you show from where this.props.data.nav comes from? Maybe when the component mounts, this.props.data or this.props.data.nav is undefined. React dev tool shows the array because after the error, this.props.data.nav is already set and not undefined. Try something like:
var nav = null;
if(this.props.data != undefined && this.props.data.nav != undefined){
nav = this.props.data.nav.map(i => "<li>${i}</li>")
}
You get map is undefined cause you don't get an array. You can't map undefined. The way I will do this will be to get an empty array if I don't have the props yet. This way you can still map over it but receive no element
class Header extends Component {
render() {
const navData = this.props.data && this.props.data.nav || []
const nav = navData.map(i => `<li>${i}</li>`)
return (
<div className="header">
<div className="left">
<h1>{this.props.data.name}</h1>
<p>{this.props.data.tag}</p>
</div>
<div className="right">
<h2>{this.props.data.t1}</h2>
<h3>{this.props.data.t2}</h3>
</div>
<div className="header-contact">
<a rel="noopener" href="tel:+14156943568"><FontAwesomeIcon icon={faPhone} /> {this.props.data.phone}</a>
<a rel="noopener" href="mailto:tim.smith.hdg#gmail.com"><FontAwesomeIcon icon="at" /> {this.props.data.email}</a>
</div>
<nav id="nav" className='nav'>
<ul>
{
//nav
}
</ul>
</nav>
</div>
);
}
}
Or you can handle this case from the parent also
class Parent extends Component {
render() {
return (
<div>
<Header data={this.state.header} nav={this.state.header && this.state.header.nav || []} />
</div>
)
}
}
class Header extends Component {
render() {
const nav = this.props.nav.map(i => `<li>${i}</li>`)
return (
<div className="header">
<div className="left">
<h1>{this.props.data.name}</h1>
<p>{this.props.data.tag}</p>
</div>
<div className="right">
<h2>{this.props.data.t1}</h2>
<h3>{this.props.data.t2}</h3>
</div>
<div className="header-contact">
<a rel="noopener" href="tel:+14156943568"><FontAwesomeIcon icon={faPhone} /> {this.props.data.phone}</a>
<a rel="noopener" href="mailto:tim.smith.hdg#gmail.com"><FontAwesomeIcon icon="at" /> {this.props.data.email}</a>
</div>
<nav id="nav" className='nav'>
<ul>
{
//nav
}
</ul>
</nav>
</div>
);
}
}