put elements into variable for naming (react) - reactjs

I tried to put elements into CustomModal variable:
const CustomModal = (<div className="peoplelistpage-modal">
<div className="peoplelistpage-modal-content-empty" />
<div className="peoplelistpage-modal-content">
<CustomForm
krNameInput={this.state.krNameInput}
handleKrNameInput={this.handleKrNameInput}
enNameInput={this.state.enNameInput}
handleEnNameInput={this.handleEnNameInput}
positionInput={this.state.positionInput}
handlePositionInput={this.handlePositionInput}
departmentInput={this.state.departmentInput}
handleDepartmentInput={this.handleDepartmentInput}
doingInput={this.state.doingInput}
handleDoingInput={this.handleDoingInput}
btnValue="add"
onBtnClick={this.handlePersonAddBtn}
/>
</div>
<div className="peoplelistpage-modal-content-empty" />
</div>);
and used it in render() like this:
render() {
//...
{ CustomModal }
//...
but, got an error:
react-dom.development.js:57 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {CustomModal}). If you meant to render a collection of children, use an array instead.
Is there are any way to put elements into variable for naming?
Thanks.
----update-----
This is my full code of render :
render() {
const CustomModal = (<div className="peoplelistpage-modal">
<div className="peoplelistpage-modal-content-empty" />
<div className="peoplelistpage-modal-content">
<CustomForm
krNameInput={this.state.krNameInput}
handleKrNameInput={this.handleKrNameInput}
enNameInput={this.state.enNameInput}
handleEnNameInput={this.handleEnNameInput}
positionInput={this.state.positionInput}
handlePositionInput={this.handlePositionInput}
departmentInput={this.state.departmentInput}
handleDepartmentInput={this.handleDepartmentInput}
doingInput={this.state.doingInput}
handleDoingInput={this.handleDoingInput}
btnValue="add"
onBtnClick={this.handlePersonAddBtn}
/>
</div>
<div className="peoplelistpage-modal-content-empty" />
</div>);
const { people } = this.props.people.state;
return (
<React.Fragment>
{/* check login */}
{this.props.auth.state.isLoggedIn ? (
{ CustomModal }
) : (
<div />
)}
<div className="peoplelistpage-main">
<h1 className="peoplelistpage-title">people list</h1>
<div className="peoplelistpage-list-container">
{people.map((person, index) => (
<ul className="peoplelistpage-list-ul" key={index}>
<li className="peoplelistpage-list-li">
{`${index + 1}.`}{" "}
<Link to={`${this.props.location.pathname}/${person.id}`}>
{person.kr_name}
</Link>{" "}
<button onClick={this.handlePersonDeleteBtn(person.id)}>
<DeleteUserIcon />
</button>
</li>
</ul>
))}
</div>
<button onClick={this.openModal}>add</button>
</div>
</div>
) : (
<CustomNotPermittedForm />
)}
</React.Fragment>
);
}

Yes, you can use a div or a React.Fragment to group elements together. divs are added to the DOM while Fragments are not. But in order for this work with state, you will have to use a function, as a static variable does not get updated with state values.
const CustomModal = () => (
<React.Fragment> // <-- or div
<div className="peoplelistpage-modal">
<div className="peoplelistpage-modal-content-empty" />
<div className="peoplelistpage-modal-content">
<CustomForm
krNameInput={this.state.krNameInput}
handleKrNameInput={this.handleKrNameInput}
enNameInput={this.state.enNameInput}
handleEnNameInput={this.handleEnNameInput}
positionInput={this.state.positionInput}
handlePositionInput={this.handlePositionInput}
departmentInput={this.state.departmentInput}
handleDepartmentInput={this.handleDepartmentInput}
doingInput={this.state.doingInput}
handleDoingInput={this.handleDoingInput}
btnValue="add"
onBtnClick={this.handlePersonAddBtn}
/>
</div>
<div className="peoplelistpage-modal-content-empty" />
</div>
</React.Fragment>
);
Usage
render() {
// ...
<CustomModal />
// ...

Related

How filter an object in component with props?

I would like to filter and display onclick the choice by id in a component by props.
APP COMPONENT: I display the list
<div className="App-container">
<div className="App-container-left">
<p>Liste des factures</p>
<div>
{datas.factures.map((datas) => (
<>
<ul>
<li key={datas.id}>
N° : {datas.id}|{datas.dateFacture}-{datas.client} -
Montant : {datas.montant} €
</li>
<button onClick={toggleFact} id={datas.id}>
Voir
</button>
</ul>
</>
))}
</div>
</div>
<div className="App-container-right">
{view && <ViewFact obj={datas} selectId={datas.id} />}
</div>
<div />
</div>
CHILD COMPONENT: onclick I would like display the id
export default function ViewFact(props) {
//filter with id
const filtered = props.obj.factures.filter((id) => {
return props.obj.factures.id === id;
});
return (
<>
<div>ViewFact Component</div>
<div>
{filtered.map((datas) => (
<>
<ul>
<li key={datas.id}>
N° : {datas.id}|{datas.dateFacture}-{datas.client} - Montant :{" "}
{datas.montant} €
</li>
</ul>
</>
))}
</div>
</>
);
}
If I understood correctly, you need to see the clicked item details, so
<ViewFact obj={datas} selectId={datas.id} />
should has as input only the clicked item. (you need to implement setCurrentSelectedItem so as to store the item in your local state)
<button onClick={setCurrentSelectedItem}>
Voir
</button>
<ViewFact obj={currentSelectedItem} />
and finally your compoment will be
export default function ViewFact({ datas }) {
return (
<>
<div>ViewFact Component</div>
<div>
N° : {datas.id}|{datas.dateFacture}-{datas.client} - Montant :{" "}
{datas.montant} €
</div>
</>
);
}

How to pass state properties from component to component

I am currently learning React and I am trying to create a basic todo list app. I am facing an issue in the understanding of how passing data from component to component.
I need that when I add a task in the modal of my home component it gets added in the "pub" state of my public task component in order for the task to be rendered.
I joined the code of both components,
Hope someone can help me :)
function PublicTask (){
const [pub,setPub] = useState([{id: 1, value : "test"},{id: 2, value : "test2"}]);
function ToDoPublicItem() {
const pubT = pub.map(value =>{
return(
<div className= 'pubTask-item'>
<li>{value.value}</li>
</div>
)
});
return(
<div>
<div>
{pubT}
</div>
</div>
);
}
return(
<div className= 'item-container'>
<h2 style={{color:'white'}}>Public Tasks</h2>
<ToDoPublicItem/>
</div>
);
}
export default PublicTask;
function Home() {
const [show,setShow] = useState(false);
const [pubTask,setPubTask] = useState([]);
function openModal() {
setShow(true);
}
function Modal(){
const[textTodo, setTextTodo] = useState('')
const addItem = () => {
const itemTopush = textTodo;
pubTask.push(itemTopush);
}
return(
<div className='modal'>
<div className = 'modal-title'>
<h2>ADD A TODO</h2>
<hr></hr>
</div>
<div className= 'modal-body'>
<input type='text' onChange = {(e) => setTextTodo(e.target.value)}/>
<input type="checkbox" id="pub" value ='public'/>
<label Htmlfor="pub">Public</label>
<input type="checkbox" id="priv" value= 'private '/>
<label Htmlfor="riv">Private</label>
<hr></hr>
<Button id='button-add' size='large' style={{backgroundColor : 'white'}} onClick={()=> addItem()}>ADD</Button>
<hr></hr>
<Button id='button-close' size='large' style={{backgroundColor : '#af4c4c'}} onClick= {()=> setShow(false)} >CLOSE</Button>
</div>
</div>
)
}
return(
<div>
<h1 style={{textAlign:'center'}}>You are logged in !</h1>
<div>
<button id='button-logout' onClick = {() => firebaseApp.auth().signOut()}>Logout</button>
</div>
<div>
<Fab color="primary" aria-label="add" size = 'large' onClick = {() => openModal()}>
<Add/>
</Fab>
{show ? <Modal/> : <div></div>}
</div>
<div>
<Router>
<div className='pub-container'>
<Link to='/publicTasks'>Public Tasks </Link>
</div>
<div className='ongo-container'>
<Link to='/onGoingTasks'>On Going Tasks </Link>
</div>
<div className='finish-container'>
<Link to='/finishedTasks'>Finished Tasks </Link>
</div>
<Route path='/publicTasks' component = {PublicTask}/>
<Route path='/onGoingTasks' component = {OngoingTask}/>
<Route path='/finishedTasks' component = {FinishedTask}/>
</Router>
</div>
</div>
);
}
export default Home;
You can share data between react components like this:
const [value, setValue] = useState("test"); // data that you want to share
return (
<Parent data={value}> // pass data to parent in your child component
);
<h1>{this.props.data}</h1> // do something with the data in the parent component

React Hover to conditional render component

this is my code so far
class PortfolioList extends Component{
render(){
const {column , styevariation } = this.props;
const list = PortfolioListContent.slice(0 , this.props.item);
return(
<React.Fragment>
{list.map((value , index) => (
<div className={`${column}`} key={index}>
<div className={`portfolio ${styevariation}`}>
<div className="thumbnail-inner" >
<div className={`thumbnail ${value.image}`}></div>
<div className={`bg-blr-image ${value.image}`}></div>
</div>
<div className="content" >
<div className="inner">
<p>{value.category}</p>
<h4>{value.title}</h4>
<div className="btn-container">
<div className="portfolio-button">
<a className="rn-btn" href="/portfolio-details"><FaGithub /> Git </a>
</div>
<div className="portfolio-button">
<a className="rn-btn" href="/portfolio-details"><FaExternalLinkAlt /> Live </a>
</div>
</div>
</div>
</div>
</div>
</div>
))}
</React.Fragment>
)
}
}
I want to conditionally render the div "content" and the child elements of content div when mouse is hovering over "thumbnail-inner" div. But hide content when mouse is not hovering over thumbnail-inner div.
How can i achieve this?
I didn't test this, but the idea is to add a variable in the state of the component which holds the current hovered item.
When a mouseEnter event enters to your thumbnail-inner, you update that variable with the current component index. And you set it to -1 when a mouseLeave events happens in your thumbnail-inner.
Then you simply render the content conditionally by checking if the this.state.selectedIndex === index.
class PortfolioList extends Component {
state = {
selectedItem: -1,
}
render(){
const {column , styevariation } = this.props;
const list = PortfolioListContent.slice(0 , this.props.item);
return(
<React.Fragment>
{list.map((value , index) => (
<div className={`${column}`} key={index}>
<div className={`portfolio ${styevariation}`}>
<div
className="thumbnail-inner"
onMouseEnter={ () => { this.setState({selectedItem: index}) } }
onMouseLeave={ () => { this.setState({selectedItem: -1}) } }>
<div className={`thumbnail ${value.image}`}></div>
<div className={`bg-blr-image ${value.image}`}></div>
</div>
{
this.state.selectedItem === index &&
<div className="content" >
<div className="inner">
<p>{value.category}</p>
<h4>{value.title}</h4>
<div className="btn-container">
<div className="portfolio-button">
<a className="rn-btn" href="/portfolio-details"><FaGithub /> Git </a>
</div>
<div className="portfolio-button">
<a className="rn-btn" href="/portfolio-details"><FaExternalLinkAlt /> Live </a>
</div>
</div>
</div>
</div>
}
</div>
</div>
))}
</React.Fragment>
)
}
First, you need to add state for condition of hover (ex: "onHover"), the state is for conditional rendering the <div className="content">.
Second you need create function for hover and leaveHover(onMouseEnter & onMouseLeave) we call it handleMouseEnter for onMouseEnter, and we call it handleMouseLeave for onMouseLeave.
class PortfolioList extends Component {
state = {
onHover: false,
}
handleMouseEnter() {
this.setState({onHover: true})
}
handleMouseLeave() {
this.setState({onHover: false})
}
render(){
const {column , styevariation } = this.props;
const list = PortfolioListContent.slice(0 , this.props.item);
return(
<React.Fragment>
{list.map((value , index) => (
<div className={`${column}`} key={index}>
<div className={`portfolio ${styevariation}`}>
<div
className="thumbnail-inner"
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}>
<div className={`thumbnail ${value.image}`}></div>
<div className={`bg-blr-image ${value.image}`}></div>
</div>
{
this.state.onHover &&
<div className="content" >
<div className="inner">
<p>{value.category}</p>
<h4>{value.title}</h4>
<div className="btn-container">
<div className="portfolio-button">
<a className="rn-btn" href="/portfolio-details"><FaGithub /> Git </a>
</div>
<div className="portfolio-button">
<a className="rn-btn" href="/portfolio-details"><FaExternalLinkAlt /> Live </a>
</div>
</div>
</div>
</div>
}
</div>
</div>
))}
</React.Fragment>
)
}

Javascript - Return two outputs through an array.map()

I have the following return in a react component:
render() {
return(
<div>
<div className = "category-name">
{categories.map(category =>
<p>{category.name}</p>
)}
</div>
<div className = "category-name">
{categories.map(category =>
<Playlist categoryid={category.id}/>
)}
</div>
</div>
);
}
This is displaying names of categories and then going through the array of names getting the description from the Playlist component.
Could someone tell me how I would return the playlists under each name? I tried the following but it just won't work:
render() {
return(
<div>
<div className = "category-name">
{categories.map(category =>{
return (<p>{category.name}</p>,
<Playlist categoryid={category.id}/>)
}
)}
</div>
</div>
);
}
You could used react fragments, using their full syntax <React.Fragment> allows you to put a key attribute within them :
<div className = "category-name">
{categories.map(category => {
return
<React.Fragment key={category.id}>
<p>{category.name}</p>,
<Playlist categoryid={category.id}/>
</React.Fragment>
}
)}
</div>
The <React.Fragment> element will not be rendered in the DOM and allows you to put any elements within them.
You need to wrap your elements in map function in some html tag or React.Fragment:
render() {
return(
<div>
<div className = "category-name">
{categories.map(category => (
<div key={category.id}>
<p>{category.name}</p>
<Playlist categoryid={category.id}/>
</div>
)
)}
</div>
</div>
);
}
And please, don't forget to use key in your cycles

Cannot read property 'image_url' of undefined in React

I am very new to react and I am trying to show data
but I am getting the error
No Data is appear when i add some code about image_url, title,source_url etc....
TypeError: Cannot read property 'image_url' of undefined
In Recipe.js,
import React, { Component } from 'react'
export default class Recipe extends Component {
render() {
const {
image_url,
title,
source_url,
publisher,
recipe_id
} = this.props.recipe;
return (
<React.Fragment>
<h1>Recipe</h1>
<div className="col-10 mx-auto col-md-6 col-lg-4">
<div className="card">
<img src={image_url} className="img-card-top" style={{height:"14rem"}} alt="recipe" />
<div className="card-body text-capitalize">
<h5>{title}</h5>
<h6 className="text-warning text-slanted">
provided by {publisher}
</h6>
</div>
<div className="card-footer">
<button type="button" className="btn btn-outline-primary">Details</button>
Recipe url
</div>
</div>
</div>
</React.Fragment>
);
}
}
In ReactList.js,
<div className="row">
{recipes.map (recipe => {
return <Recipe key={recipe.recipe_id} recipe={recipe}
/>;
})}
</div>
</div>
<Recipe />
</React.Fragment>
error occur as you use two time <Recipe /> in RecipeList.js,
Removed one <Recipe />,
error will solve
Change
<div className="row">
{recipes.map (recipe => {
return <Recipe key={recipe.recipe_id} recipe={recipe}
/>;
})}
</div>
</div>
<Recipe />
</React.Fragment>
To
<div className="row">
{recipes.map (recipe => {
return <Recipe key={recipe.recipe_id} recipe={recipe}
/>;
})}
</div>
</div>
</React.Fragment>

Resources