I have a page in my react site that will load an option box of values retrieved from the server and when the user selects an item from the box, I then make another call to the server for different data (file names and a URL to download the file).
What I can't get working is two things 1) when I select an item from the box, I get to a new page that doesn't have my header and other items that show after the render() call. 2) I can iterate through my array and get the items I need but none of my href links show.
itemSelect(event){
params.fileName= event.currentTarget[1].name
restAPI.put(`/api/customers/files`, {params: event.nativeEvent.srcElement.value}).then(res =>{
const element = (
<div>
{Object.entries(res.data).forEach(key => {
if(key[1].name.length > 0){
console.log('url', key[1].url)
console.log('name', key[1].name)
return <a href={key[1].url}>{key[1].name}</a>
}
})}
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
return ReactDOM.render(element, document.getElementById('root'));
})
}
render() {
const { folderList = {} } = this.state;
return (
<div id="root">
<select name='folderListing' onChange={this.itemSelect.bind(this)}>
{Object.values(folderList).map(function(item) {
return <option key={item} name={item} id={item} value={item}>{item} </option>
})}
</select>
</div>
)
}
You are losing your elements because of this line:
return ReactDOM.render(element, document.getElementById('root'));
You are effectively replacing your entire app with element. Instead, use the returned element in your render method:
state = {
links: null,
folderList: {}
};
itemSelect(event){
params.fileName= event.currentTarget[1].name
restAPI.put(`/api/customers/files`, {params: event.nativeEvent.srcElement.value}).then(res =>{
const element = (
<div>
{Object.entries(res.data).forEach(key => {
if(key[1].name.length > 0){
console.log('url', key[1].url)
console.log('name', key[1].name)
return <a href={key[1].url}>{key[1].name}</a>
}
})}
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
this.setState({
links: element
});
});
}
render() {
const { folderList = {}, links } = this.state;
return (
<div id="root">
<select name='folderListing' onChange={this.itemSelect.bind(this)}>
{Object.values(folderList).map(function(item) {
return <option key={item} name={item} id={item} value={item}>{item} </option>
})}
</select>
{links}
</div>
)
}
Related
I am wondering the best way to tackle this problem.
I intend to create a state in the parent component of my application, pass the set state to a component that holds the button (sibling A), and the value to another component where it will be displayed and updated (sibling B). I have a rough idea of how to do this, but ultimately I am lost and am seeking direction. Thank you!
My parent component is as follows
//playlist state
const [playlistItem, setPlaylistItem] = useState()
const mainCards = Data.map(card => {
return(
<MainCard
key={card.id}
id={card.id}
image={card.url}
title={card.title}
playbutton={card.playbutton}
addbutton={card.addbutton}
playlistState={setPlaylistItem}
/>
)
})
const sideCards = SideData.map(card => {
return(
<SideCard
image={card.sideurl}
key={card.id}
title={card.sidetitle}
playbutton={card.playbutton}
addbutton={card.addbutton}
playlistItem={playlistItem}
/>
)
})
return (
<div className="App">
{console.log("main cards" + mainCards[0])}
{console.log("side cards" + sideCards.sidetitle)}
<Navbar />
<Header />
<Playlist />
<CardContainer />
<div className="maincards">
{mainCards}
</div>
<div className="sidecards">
{sideCards}
</div>
</div>
)
}
Sibling A
const handleAdd = (id) => {
console.log(id)
}
return(
<div>
<div className="mainCardObject">
<div className="cardObj">
<img src={props.image} className ="mainCardImage"/>
<img src={props.playbutton} className="playbutton"/>
<img src={props.addbutton} onClick={() => handleAdd(props.id)} className="addbutton" />
</div>
</div>
</div>
)
}
Sibling B
function Playlist(props){
return(
<div className="playlistContainer">
<ul>
<li></li>
</ul>
</div>
)
}
You can pass both getter and setter as parameters, and use them normally in your components:
Sibling A
const handleAdd = (id) => {
//your logic
props.playlistState(prevValue => [])
}
Sibling B
return (
<div className="playlistContainer">
<ul>
<li>
{props.playlistItem}
</li>
</ul>
</div>
)
You can also create a function in your parent component, using set state, and pass this function as a parameter to your component:
Parent
const addPlayListItem = (playListItem) => {
setPlaylistItem(prev => [...prev, playListItem])
}
return (
<SiblingA
addPlayListItem={addPlayListItem}
/>
)
Sibling A
function MainCard(props) {
const handleAdd = () => {
//your logic
props.addPlayListItem({ name: 'rock', title: 'Foo Fighters', year: 2011 })
}
return (
<div>
<img src={props.addbutton} onClick={handleAdd} className="addbutton" />
</div>
)
}
Sibling A:
const handleAdd = (id) => {
props.playlistState((prev) => ([...prev, id]))
}
I have an array of files and I want certain ones to be displayed and hyperlinked. I'm using the map method and when only 1 file displays, it links properly. I need some help with the syntax when multiple files must be displayed.
render() {
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
}
if (this.props.channelSelectedData.length >= 1){
return(
<div className="channel-detail-box">
<p>Outages:
<a href={mappings[this.props.channelSelectedData.map(inspection => {
return inspection.outage
})]}>
{this.props.channelSelectedData.map(inspection => {
return inspection.outage + ' '
})}</a>
</p>
</div>
)
}
else {
return (
<div>
<p>No data found</p>
</div>
)
}
}
}
Is this what you are looking for ?
render() {
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
}
const { channelSelectedData } = this.props
if (channelSelectedData.length === 0) {
return <div>
<p>No data found</p>
</div>
}
return <div className="channel-detail-box">
<p>Outages: {channelSelectedData.map(({ outage }) => <a href={mappings[outage]}>{outage}</a>)}</p>
</div>
}
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
};
if (!channelSelectedData || channelSelectedData.length <= 0) {
return (
<div>
<p>No data found</p>
</div>
);
}
const links = channelSelectedData.map(({ outage }) => (
<a href={mappings[outage]}>{outage}</a>
));
return (
<div className="channel-detail-box">
<p>Outages: {links}</p>
</div>
);
If I am understanding the rest of your question correctly, I believe your issue is just using map at the incorrect point. What map does is returns an array of values which in this case would be an array of applicable tags.
render() {
const mappings = {
'P1011': 'http://192.168.191.128:8080/Pickering-P1011-May-Verified_Results5.xls',
'P1511': 'http://192.168.191.128:8080/PNGS-1511-Verified_Results_2.xls',
'P1711': 'http://192.168.191.128:8080/PNGS-P1711_Verified_Results_3.xlsx',
'P1911': 'http://192.168.191.128:8080/PLGS_Unit_1-PL1911_VerifiedResults2.xlsx',
}
if (this.props.channelSelectedData.length >= 1){
return(
<div className="channel-detail-box">
<p>Outages:
<>
{
this.props.channelSelectedData.map(chanel=>{
return (
<a href={mappings[chanel]}>
{chanel+' '}
</a> )
})
}
</>
</p>
</div>
)
}
else {
return (
<div>
<p>No data found</p>
</div>
)
}
}
I've read the documentation, I don't know why it's working but it's messed up. Here's my code :
function CarouselItem(props) {
const { post } = props
return (
<React.Fragment>
<div>
<img src={`http://localhost:5000/image/${post.foto}`} />
<p className="legend">{post.judul}</p>
</div>
</React.Fragment>
)
}
function NewsItem(props) {
const { posts } = props.post
let content = posts.map(item => <CarouselItem key={item._id} post={item} />)
return (
<div>
<Carousel showThumbs={false}>{content}</Carousel>
</div>
)
}
It turns out like this :
Use this in the first line of your .js file:
import 'react-responsive-carousel/lib/styles/carousel.min.css';
render() {
const tableStyle = this.getTableStyle();
const tableSettings = this.getTableSettings();
return (
<div style={tables}>
<TablePosition
contextMenuOn={true}
step={this.props.step}
pdfData={this.props.pdfData}
tableSettings={tableSettings}
tableStyle={tableStyle}
fileName={this.state.fileName}
tableSize={this.getTableSize()}
tableOffset={this.state.tableOffset}
desiredWidth={700}
updateXOffset={x => this.updateXOffset(x)}
updateYOffset={y => this.updateYOffset(y)}
markTable={() => this.markTable()}
setOutputLabels={(row, col, val) => this.setOuputLabels(row, col, val)}
/>
</div>
);
if (!this.props.isThirdStep) {
return (
<div>
<div style={sideBySide}>
<PDFViewer
isThirdStep={this.props.isThirdStep}
paginationCallback={this.handlePageChange}
pdfData={this.state.pdfData}
desiredWidth={600}
selectedPage={this.props.savedPageNo}
/>
</div>
</div>
);
} else {
return (
<div>
<ReferenceMenu />
</div>
);
}
}
In my component's render, I try to render several components based on certain conditions.
So, basically, the TablePoisition always stays there, and the PDFViewer and ReferenceMenu renders conditionally.
However, what I see on both conditions is only the TablePosition component.
Is this not supposed to work?
As explained since you want to combine two components you should change your render logic. One component will be sit there always and the other one will be rendered conditionally. So, you need to render that last component with the sticky one in the same return. I would do something like this:
renderPDFViewer = () => (
<div>
<div style={sideBySide}>
<PDFViewer
isThirdStep={this.props.isThirdStep}
paginationCallback={this.handlePageChange}
pdfData={this.state.pdfData}
desiredWidth={600}
selectedPage={this.props.savedPageNo}
/>
</div>
</div>
);
render() {
const tableStyle = this.getTableStyle();
const tableSettings = this.getTableSettings();
return (
<div>
<div style={tables}>
<TablePosition
contextMenuOn={true}
step={this.props.step}
pdfData={this.props.pdfData}
tableSettings={tableSettings}
tableStyle={tableStyle}
fileName={this.state.fileName}
tableSize={this.getTableSize()}
tableOffset={this.state.tableOffset}
desiredWidth={700}
updateXOffset={x => this.updateXOffset(x)}
updateYOffset={y => this.updateYOffset(y)}
markTable={() => this.markTable()}
setOutputLabels={(row, col, val) => this.setOuputLabels(row, col, val)}
/>
</div>
{
!this.props.isThirdStep
? this.renderPDFViewer()
: ( <div><ReferenceMenu /></div> )
}
</div>
);
}
You need to place your conditional renders inside variables or something similar.
var conditionContent1 = null;
var conditionContent2 = null;
if(condition1){
conditionContent1 = <div>conditional content 1</div>;
}
if(condition2){
conditionContent2 = <div>conditional content 2</div>;
}
return (
<div id="wrapper">
<div>
content
</div>
{conditionContent1}
{conditionContent2}
</div>
);
I added a wrapper div; because, I believe render's return doesn't like having multiple root elements.
If the variables are null; then, it won't affect the overall render.
Ultimately I'm trying to pass mapped elements in an array to a child component. I made a WordPress API call to get back posts for a preview page, and now that I'm trying to have that data render in their own pages, I keep getting that the data is undefined. The dynamic links are rendering as expected, but none of the other data is being passed.
Articles.js
// cut for brevity
render() {
let articles = this.state.newsData.map((article, index) => {
if(this.state.requestFailed) return <p>Failed!</p>
if(!this.state.newsData) return <p>Loading...</p>
return(
<div key={index} className="article-container">
<div className="article-preview">
<span className="article-date">{article.date}</span>
<h5>{article.title.rendered}</h5>
<div dangerouslySetInnerHTML={{ __html: article.excerpt.rendered }} />
<Link to={`/news/${article.slug}`}>Read More...</Link>
</div>
<Route path={`/news/:articleSlug`}
render={ props => <Article data={article} {...props} />}
/>
</div>
)
});
return (
<div>
<h3>All Articles from Blog</h3>
{articles}
</div>
)
}
Article.js
import React from 'react';
const Article = ({match, data}) => {
let articleData;
{ console.log(this.data) }
if(data)
articleData = <div>
<h3> {data.title.rendered}</h3>
<div dangerouslySetInnerHTML={{ __html: data.content.rendered }} />
<hr />
</div>
else
articleData = <h2> Sorry. That article doesn't exist. </h2>;
return (
<div>
<div>
{articleData}
</div>
</div>
)
}
export default Article;
How do I get the data from the array into the Article component?
Your problem is with asynchronous requests.
You have a route that will call the render method when the user clicks on a link. At that point in time, javascript has no reference to the article anymore, you need to persist it.
Here's an example of what you are experiencing
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 1);
}
The code above will always log 10
A solution to this problem is using bind.
for (var i = 0; i < 10; i++) {
setTimeout(function(i) { console.log(i); }.bind(null, i), 1);
}
So, in your code, you need to persist the article variable.
You can do that by calling a method that takes the data.
renderArticle(data) {
return props => <Article data={data} {...props} />
}
render() {
let articles = this.state.newsData.map((article, index) => {
if(this.state.requestFailed) return <p>Failed!</p>
if(!this.state.newsData) return <p>Loading...</p>
return(
<div key={index} className="article-container">
<div className="article-preview">
<span className="article-date">{article.date}</span>
<h5>{article.title.rendered}</h5>
<div dangerouslySetInnerHTML={{ __html: article.excerpt.rendered }} />
<Link to={`/news/${article.slug}`}>Read More...</Link>
</div>
<Route path={`/news/:articleSlug`}
render={this.renderArticle(article)}
/>
</div>
)
});
return (
<div>
<h3>All Articles from Blog</h3>
{articles}
</div>
)
}
Hope this points you in the right direction.