Passing state back to child component - reactjs

I'm trying to figure out how can i properly pass state back to the child component.
Currently I have list of items and everytime i click on one of the items it changes state of "selectedVideo" variable in parent component. And then I would like to add class to the item that corresponds to that state in that child component. Basically when I click on that item in that list it become highlighted because it just changed the state of parent component.
So the main parent component is here:
index.js
class App extends Component {
constructor(props) {
super(props)
this.state = {
videos2:[],
selectedVideo:null
}
this.DMSearch()
}
DMSearch(term){
fetch(`https://api.dailymotion.com/videos?fields=description,id,thumbnail_60_url,title,url,&limit=5&search=${term}`)
.then(result => result.json())
.then(videos2 => {
//console.log(videos2.list[0]);
this.setState({
videos2: videos2.list,
selectedVideo: videos2.list[0]
});
//console.log(this.state.selectedVideo);
});
}
render () {
const DMSearch = _.debounce((term) => { this.DMSearch(term)}, 400);
return (
<div>
<SearchBar onSearchTermChange= {DMSearch}/>
<VideoDetail video={this.state.selectedVideo}/>
<VideoList
onVideoSelect={selectedVideo=>this.setState({selectedVideo})}
videos2={this.state.videos2}/>
</div>
)
}
}
Now the child component which changes state onclick
video_list_item.js
const VideoListItem = ({video, onVideoSelect}) => {
const imageUrl = video.thumbnail_60_url;
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-obj" src={imageUrl}/>
</div>
<div className="media-body">
<div className="media-heading">{video.title}</div>
</div>
</div>
</li>
);
};
And what I want is to add class "active" to this specific line
<li onClick={() => onVideoSelect(video)} className="list-group-item">
Based on the state of selectedVideo that changed in index.js after clicking on that component.
Also here is the code for the whole list.
video_list.js
const VideoList = (props) => {
const videoItems = props.videos2.map((video)=>{
return (
<VideoListItem
onVideoSelect={props.onVideoSelect}
key={video.id}
video={video} />
)
})
return (
<ul className="col-md-4 list-group">
{videoItems}
</ul>
)
}

You have to pass the selectedVideo state of your App to the VideoList component,
<VideoList
videos2={this.state.videos2}
onVideoSelect={selectedVideo=>this.setState({selectedVideo})}
selectedVideo={this.state.selectedVideo}
/>
which in turn passes it to each VideoListItem
const videoItems = props.videos2.map((video)=>{
return (
<VideoListItem
onVideoSelect={props.onVideoSelect}
key={video.id}
video={video}
active={video === props.selectedVideo}
/>
)
})
so each item can compare itself to the selectedVideo and display an 'active' class if needed.

Related

How to change a style of an HTML element in React?

I have two React components
class App extends React.Component {
render() {
return (
<div id="appWrapper">
<ConfigureWindow />
<button id="configureClocksButton">Configure clocks</button>
<section id="clocksHere"></section>
</div>
);
}
}
const ConfigureWindow = () => (
<div id="configureWindowWrapper">
<div id="configureWindow">
<section id="addCitySection">TODO: adding a city</section>
<div id="verticalLine"></div>
<section id="listOfCities">
<header>
<h1>Available cities</h1>
<div id="closeConfigureWindowWrapper">
<img src="..\src\images\exit.png" id="closeConfigureWindow" alt="" />
</div>
</header>
<section id="availableCities"></section>
</section>
</div>
</div>
);
I want "ConfigureWindow" to be shown when "configureClocksButton". I tried to execute it with props, state and a function but got errors. It also would be nice if you explain me how to create new React components with React functions?
You probably want to use the React.JS event onClick (https://reactjs.org/docs/handling-events.html), and a state to store the action. To create a function component, you just have to return the JSX you want to render, and use hooks (https://reactjs.org/docs/hooks-intro.html) and then do a conditional rendering (https://reactjs.org/docs/conditional-rendering.html):
const App = () => {
const [toggleConfiguration, setToggleConfiguration] = useState(false)
return (
<div id="appWrapper">
{toggleConfiguration && <ConfigureWindow />}
<button onClick{() => setToggleConfiguration(true)} id="configureClocksButton">Configure clocks</button>
<section id="clocksHere"></section>
</div>
);
}
It's a bit difficult to understand your post, but I gather you want to click the button with id="configureClocksButton" and conditionally render the ConfigureWindow component.
You can accomplish this with some boolean state, a click handler to toggle the state, and some conditional rendering.
class App extends React.Component {
this.state = {
showConfigureWindow: false,
}
toggleShowConfigureWindow = () => this.setState(prevState => ({
showConfigureWindow: !prevState.showConfigureWindow,
}))
render() {
return (
<div id="appWrapper">
{showConfigureWindow && <ConfigureWindow />}
<button
id="configureClocksButton"
onClick={this.toggleShowConfigureWindow}
>
Configure clocks
</button>
<section id="clocksHere"></section>
</div>
);
}
}
A function component equivalent:
const App = () => {
const [showConfigureWindow, setShowConfigureWindow] = React.useState(false);
const toggleShowConfigureWindow = () => setShowConfigureWindow(show => !show);
return (
<div id="appWrapper">
{showConfigureWindow && <ConfigureWindow />}
<button
id="configureClocksButton"
onClick={toggleShowConfigureWindow}
>
Configure clocks
</button>
<section id="clocksHere"></section>
</div>
);
}

Child Not Re-rendering on List Item Deletion in Parent but Adding to the List Item Triggering Re-render

I have Simple Add and Delete to my List sample ..
I made two child components
Lead Form Component ( Which Add New Leads to the List )
Lead List Component ( Which Simply render Leads List also have delete button which trigger delete action by passing ID back to parent )
In parent , the.state.leads holds all the leads
on Form Submit .. it adds to the.state.leads and LEAD LIST CHILD Components
successfully Re-Renders with new added lead
but on deleting list in the LEAD LIST , The lead list not re renders
Image ; Dev Tool Debug in the browser -React Console screenshot ..
MY LeadList Component
.........................................................
class LeadList extends React.Component {
constructor(props) {
super(props);
this.state = {
leads: this.props.avlList
};
this.handelDeleteLead = this.handelDeleteLead.bind(this);
}
handelDeleteLead(e) {
e.preventDefault();
this.props.DeleteLead(e.target.id);
}
render() {
console.log(this.state.leads);
return (
<div>
<ul>
{this.state.leads.map(item => (
<li key={item.id}>
{item.name} - {item.mobile} -{item.active ? "Active" : "Inactive"}
-
<div
id={item.id}
onClick={this.handelDeleteLead}
cursor="pointer"
>
X
</div>
</li>
))}
</ul>
</div>
);
}
}
......
My APP.js Parent Componnet
....................................
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
leads: [{ id: 1, name: "Panindra", mobile: "88842555542", active: true }]
};
this.handleAddToLeads = this.handleAddToLeads.bind(this);
this.handleRemoveLeads = this.handleRemoveLeads.bind(this);
}
handleAddToLeads(lead) {
let newleadsTemp = this.state.leads;
lead.id = Math.random() * Math.random();
newleadsTemp.push(lead);
// assign a name of list to item list
let newLeads = newleadsTemp;
this.setState({
leads: newLeads
});
}
handleRemoveLeads(lead_id) {
console.log(" Leads list before fitler ..." + this.state.leads);
let newFitleredLeads = remove(this.state.leads, lead_id);
this.setState({
leads: newFitleredLeads
});
console.log(" Leads list after fitler ..." + this.state.leads);
}
render() {
return (
<div className="App">
<h1> My First Redux</h1>
<hr />
<div className="leadList">
<LeadList
avlList={this.state.leads}
DeleteLead={this.handleRemoveLeads}
/>
</div>
<div className="leadForm">
<LeadForm NewLead={this.handleAddToLeads} />
</div>
</div>
);
}
}
.....
I think the problem is that you use state in LeadList component. Try to remove state from LeadList component. You don't need to manage multiple state's (this is important).
class LeadList extends React.Component {
render() {
return (
<div>
<ul>
{this.props.avlList.map(item => (
<li key={item.id}>
{item.name} - {item.mobile} -{item.active ? "Active" : "Inactive"}
-
<div
id={item.id}
onClick={() => this.props.DeleteLead(item.id)}
cursor="pointer"
>
X
</div>
</li>
))}
</ul>
</div>
);
}
}
And fix handleRemoveLeads function in the parent (App) component.
handleRemoveLeads(lead_id) {
console.log(" Leads list before fitler ..." + this.state.leads);
// THIS IS NOT WORKING
//let newFitleredLeads = remove(this.state.leads, lead_id);
// BETTER SOLUTION
let newFitleredLeads = this.state.leads.filter(item => item.id !== lead_id);
this.setState({
leads: newFitleredLeads
});
console.log(" Leads list after fitler ..." + this.state.leads);
}
This should work fine.
Working example (without form): https://codesandbox.io/s/charming-kowalevski-rj5nj

Map creates only one li - React

I'm making a component that creates Tabs when you click on an item in the navigation menu.
All the controls I do in the father to be able to pass the states between the brothers without problems.
As it is now my code when clicking on a menu item creates a unique <li> and shows the name. If you click on the entire menu item, it does not create a new <li>, but rather updates the old one with the new menu information.
I need that every time I press a menu item a new <li> with its content is created.
I edit my code with #technogeek1995 changes and this the final solution:
class App extends Component {
constructor(props, context){
super(props, context);
["openTabs",].forEach((method) => {
this[method] = this[method].bind(this);
});
this.state = {
navigation: {
menu: [],
},
tabs:{
tabsLi:[],
},
textvalue : "",
showtabs: true,
}
}
componentDidMount() {
fetch('json_menu.php')
.then(response => response.json())
.then(data =>{
this.setState({navigation: data});
//console.log(data)
})
}
openTabs(e, url, iframe, trdtitle){
e.preventDefault();
const state = {...this.state};
state.textvalue = trdtitle.split();
state.tabs.tabsLi.push(state.textvalue);
console.log(state.tabs.tabsLi)
this.setState({ state });
this.setState({
showtabs: false,
});
}
class Tabs extends Component {
render(){
const renderTabs = tabs =>{
return(
<div id="content-tabs" className="tabs">
{( this.props.showtabs)
? (
<>
<div className="waiting-leads">
<p>Parece que todavía no hay ningún lead...</p>
<h3>¡Ánimo, ya llega!</h3>
<img src={imgDinosaurio} alt="Dinosaurio"></img>
</div>
</>
) : (
<ul id="resizable" className="content" >
{this.props.tabs.tabsLi.map((value, index) => {
return (
<li key={index}>
<span>{value}</span>
<Icon icon="cerrar" className='ico-cerrar' onClick={remove_tab(index)}/>
</li>
)
})}
</ul>
)}
</div>
);
}
return (
<>
{renderTabs(this.props.tabs.tabsLi)}
</>
)
}
}
This is the code that is generated when you click on the menu item. The <span> is the one that is updated and no new <li> is created. Ventas is my element menu name.
<ul id="resizable" class="content">
<li>
<span>Ventas</span>
<svg class="ico-cerrar">path</svg>
</li>
</ul>
The issue appears to be related to mutating the state directly. You should see some warnings in the console/terminal about mutating react's state directly. I have updatd your openTabs function so that it no longer mutates the state directly. Instead, I copy state to a local variable, perform the mutations of the local state object. Then, I call setState with the locally updated state object. React will automatically pick up the changes to the state and render the page with the (newly) updated state.
openTabs(e, url, iframe, trdtitle){
e.preventDefault();
const state = {...this.state};
state.textvalue = trdtitle.split();
state.navigation.menu.push(state.textvalue);
state.showtabs = false;
this.setState({ state });
}
Tabs Component needed to be updated to iterate over the list, rather than over the string so it will create a <li> for every element in state.navigation.menu. remove_tab needed to be wrapped in {} instead of "" as well.
class Tabs extends Component {
render() {
return ( <
div id = "content-tabs"
className = "tabs" > {
(this.props.showTabs) ? (
<div className = "waiting-leads" >
<p> Parece que todavía no hay ningún lead... </p>
<h3> ¡Ánimo, ya llega! </h3>
<img src={imgDinosaurio} alt="Dinosaurio"/>
</div>
) : (
<ul id = "resizable" className = "content" >
{this.props.tabs.map((value, index) => (
<li key={index} >
<span>{value}</span>
<Icon icon = "cerrar" className = 'ico-cerrar' onClick={remove_tab(index)} / >
</li>
)
} </ul>
)} </div>
);
}
}
You should use the callback version of state and use the spread syntax to create new objects with new references so that React detects the change in state.
this.state.navigation.menu.push(this.state.textvalue)
Also, this line will push the old textValue and not the new one which is trdtitle.split()
openTabs(e, url, iframe, trdtitle){
e.preventDefault();
const textValue = trdtitle.split()
this.setState(state => ({
textvalue,
showtabs: false,
navigation: {
...state.navigation,
menu: [ ...state.navigation.menu, textValue ]
}
}));
}

How to fix: How to show state with onClick to div?(React)

I have sidebar with document types on it(docs, table, slider, html ..). I want that, if i click on docs element it will show docs in another div like a header.
I have 3 files: DocumentType.tsx, Sidebar.tsx and Results.tsx
In DocumentType.tsx:
import React from 'react';
const documentType = (props ) =>{
return(
<div>
<p id="fileType">{props.type}</p>
</div>
)
};
export default documentType;
In Sidebar.tsx:
typeState = {
documentTypes: [
{ type: "Dokumendid" },
{ type: "PDF" },
]
}
toDocument = () => {
this.setState({
documentTypes: [
{ type: "Dokumendid" }
console.log("Document was clicked");
]
})
}
toPdf = () => {
this.setState({
documentTypes: [
{ type: "Pdf" }
console.log("PDF was clicked")
]
})
}
render(){
return(
<a className="a" href="/search?filter%3Atype=doc" onClick={this.toDocument}>
<div className="icons dokument">
<img src={dokument} alt="dokument"/>
<a className="title">dokument</a>
</div>
</a>
<a className="a" href="/search?filter%3Atype=pdf" onClick={this.toPdf}>
<div className="icons pdf">
<img src={pdf} alt="pdf"/>
<a className="title">pdf</a>
</div>
</a>
)
}
And in Results.tsx:
...
<DocumentType />
..
You want to show a document type in Results component when a document in Sidebar component is clicked.
You have documentType state in Sidebar component and you want to pass it to Results component. So for that you can make Results component as child component of Sidebar component and pass the selected document type i.e documentType state as props.
Sidebar.js
import React, {Component} from 'react'
import Results from 'path-to-results';
class Sidebar extends Component {
state = {
// instead of using "documentType" as array
// you can make it null for initial value
documentType: null
}
// instead of using "toPDF" or "toDocument" method
// you can use single method to update the state
handleDocType = (docType) => {
this.setState({
documentType: docType
})
}
render() {
return (
<div>
// pass "document" as argument to handleDocType method
<a className="a" href="#" onClick={() => this.handleDocType('document')}>
<div className="icons dokument" >
<img src="" alt="dokument"/>
<a className="title">dokument</a>
</div>
</a>
// pass "pdf" as argument to handleDocType method
<a className="a" href="#" onClick={() => this.handleDocType('pdf')}>
<div className="icons pdf">
<img src="" alt="pdf"/>
<a className="title">pdf</a>
</div>
</a>
// checking if "documentType" is null or not
// if it is null nothing is rendered
// if it is not null then "Results" component is rendered
{ this.state.documentType && <Results type={this.state.documentType} /> }
</div>
)
}
}
Results.js
import React, { Component } from 'react'
import DocType from 'path-to-doctype'
class Results extends Component {
// .... your other codes
render() {
return (
<div>
// ....... your other codes
<DocType type={this.props.type} />
</div>
)
}
}
export default Results
DocType.js
import React from 'react';
const DocumentType = (props ) =>{
return(
<div>
<p id="fileType">{props.type}</p>
</div>
)
};
export default DocumentType;
UPDATE
If Sidebar and DocType components are children components of Results component then add documentType state to Results component and pass documentType state as props to DocType component.
Results.js
class Results extends Component {
// add state "documentType"
state = {
documentType: null
}
// add "handleDocType" method
handleDocType = (docType) => {
this.setState({
documentType: docType
})
}
// .... your other codes
render() {
return (
<div>
// .... your other codes
// pass "handleDocType" as props to Sidebar component
<Sidebar handleDocType={this.handleDocType}/>
// pass "documentType" state as props to DocType component
<DocType type={this.state.documentType} />
</div>
)
}
}
export default Results
Sidebar.js
class Sidebar extends Component {
// use "docTypeHandler" to call parent "handleDocType" method
// that updates "documentType" state in Results component
docTypeHandler = (doctype) => {
this.props.handleDocType(doctype)
}
render() {
return (
<div>
<a className="a" href="#" onClick={() => this.docTypeHandler('document')}>
<div className="icons dokument" >
<img src="" alt="dokument"/>
<a className="title">dokument</a>
</div>
</a>
<a className="a" href="#" onClick={() => this.docTypeHandler('pdf')}>
<div className="icons pdf">
<img src="" alt="pdf"/>
<a className="title">pdf</a>
</div>
</a>
</div>
)
}
}
export default Sidebar
DocType.js
const DocType = (props ) =>{
return(
<div>
<p id="fileType">{props.type}</p>
</div>
)
};
If I understood your question correctly.. you wanted to show data in a div when onClick event triggers..
lets say your state object has
state = {
data: ''
}
//clicked function
clicked =() => {
this.setState({data: 'clickedme'})
}
div element: <div onClick={this.clicked} >{this.state.data}</div>
simple example when an onClick event occurs a div and displaying the state data object..

react-redux: Rendering a component after an API call

I am building an app which uses user input and shows number of recipes and they can click on recipe card to view ingredients as well. Every time they click on recipe card I make an API call to get appropriate recipe ingredient. But I am not able to figure out how to show the component which contains the recipe ingredients. I tried with conditional routing and conditional rendering as well but couldn't find the solution.
Recipe_Template.js
export class RecipeTemplate extends Component {
renderRecipe = recipeData => {
return recipeData.recipes.map(recipeName => {
return (
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<a
href={recipeName.source_url}
target="_blank"
onClick={() => {
this.props.fetchRecipeId(recipeName.recipe_id);
}}
>
<img
src={recipeName.image_url}
className="mx-auto d-block img-fluid img-thumbnail"
alt={recipeName.title}
/>
<span>
<h3>{recipeName.title}</h3>
</span>
</a>
<span}>
<h3>{recipeName.publisher}</h3>
</span>
</div>
</div>
</div>
);
});
};
render() {
return (
<React.Fragment>
{this.props.recipe.map(this.renderRecipe)}
</React.Fragment>
);
}
}
Recipe_Detail.js
class RecipeDetail extends Component {
renderRecipeDetail(recipeData) {
return recipeData.recipe.ingredients.map(recipeIngredient => {
return <li key={recipeIngredient}>recipeIngredient</li>;
});
}
render() {
if (this.props.recipeId === null) {
return <div>Loading...</div>;
}
return <ul>{this.props.recipeId.map(this.renderRecipeDetail)}</ul>;
}
}
function mapStateToProps({ recipeId }) {
return { recipeId };
}
export default connect(mapStateToProps)(RecipeDetail);
Not entirely sure why you would need Redux here (unless it's being shared among other nested components), but I'm fairly certain you can just utilize React state.
One approach would be to configure your routes as such:
<Route path="/recipes" component={Recipes} />
<Route path="/recipe/:id" component={ShowRecipe} />
When the user sends a query, gets some results, and you display all matching recipes to a Recipes component. Each recipe then has a name (and other associated displayable data) and a clickable link:
<Link to={`/recipe/id?recipeId=${recipeId}`}>View {recipeName} Recipe</Link>
which for simplicity sake might look like:
<ul>
<Link to="/recipe/id?recipeId=08861626">View Prosciutto Bruschetta Recipe</Link>
<Link to="/recipe/id?recipeId=04326743">View Pasta Bundt Loaf Recipe</Link>
...etc
</ul>
When the user clicks on the link, react-router sends the user to the ShowRecipe component with a unique recipeId.
ShowRecipe then makes another AJAX request to get the recipe details:
ShowRecipe.js
export default class ShowRecipe extends Component {
state = { recipeDetail: '' }
componentDidMount = () => {
const { recipeId } = this.props.location.query; // <== only natively available in react-router v3
fetch(`http://someAPI/recipe/id?recipeId=${recipeId}`)
.then(response => response.json())
.then(json => this.setState({ recipeDetail: json }));
}
render = () => (
!this.state.recipeDetails
? <div>Loading...</div>
: <ul>
{this.state.recipeDetail.map(ingredient => (
<li key={ingredient}>ingredient</li>
)}
</ul>
)
}
Another approach:
Have the recipeDetails stored and available within the original fetched recipes JSON. Then map over the recipes and create multiple <Card key={recipeId} recipeName={recipeName} recipeDetail={recipeDetail} /> components for each recipe.
which for simplicity sake might look like:
<div>
{this.state.recipes.map(({recipeId, recipeName, recipeDetail}), => (
<Card key={recipeId} recipeName={recipeName} recipeDetail={recipeDetail} />
)}
</div>
Then each individual Card has it's own state:
Card.js
export default class Card extends Component {
state = { showDetails: '' }
toggleShowDetails = () => this.setState(prevState => ({ showDetails: !this.state.showDetails }))
render = () => (
<div>
<h1>{this.props.recipeName} Recipe</h1>
<button onClick={toggleShowDetails}> {`${!this.state.showDetails ? "Show" : "Hide"} Recipe<button>
{ this.state.showDetails &&
<ul>
{this.props.recipeDetail.map(ingredient => (
<li key={ingredient}>ingredient</li>
)}
</ul>
}
)
}
Therefore, by default the recipeDetail is already there, but hidden. However, when a user clicks the Card's button, it will toggle the Card's showDetails state to true/false to display/hide the recipe detail.

Resources