Why am I asking this question (main return) is finsied, but board.writer is not drawing. how can i drawing this object
if my question is wrong way plz tell me . i will fix it
i tried this way
first use map function
make like this function renderUser = ({board_SEQ, content, writer,subject}) => { parameter}
const Home = () => {
const initboard = {
board_SEQ: '',
writer: '',
content: '',
subject: ''
};
const [boards, setBoard] = useState([]);
const load = () => {
axios.get('http://www.heon.shop:8080/api/boards')
.then((res) => {
const data = res.data;
setBoard(boards => [...boards, {
board_SEQ: (data[0].board_SEQ),
writer: data[0].writer,
content: data[0].content,
subject: data[0].subject
}]);
})
.catch((error) => {
console.log("error" + error);
}
);
}
useEffect(() => {
load();
console.log("useEffect");
}, []);
const renderUser = ({board_SEQ, content, writer, subject}) => {
return (
<div>
<li>he</li>
<li>{board_SEQ}</li>
<li>{content}</li>
<li>{writer}</li>
<li>{subject}</li>
</div>
);
}
return (
<div>
{boards.map(board => {
<h1> {board.writer}</h1>
})}
</div>
);
}
export default Home;
Maybe you can try like this,
<div>
{boards.map(board => renderUser(board)}
</div>
if you want to render item directly using (add return to the map):
<div>
{boards.map(board => {
return <h1> {board.writer}</h1>;
})}
</div>
Related
So as part of my project I'm trying to ammend this boilerplate of React-Pdf-Highlighter to accept pdf highlights from flask-api instead of a local file( the example came with a local/json import) ..
I have tried to check with console.log the fetch is not the problem, but I feel for somereason the 'testHighlights' state is not what it should be .
<<App.js>>
// #flow
/* eslint import/no-webpack-loader-syntax: 0 */
import React, { Component } from "react";
import PDFWorker from "worker-loader!pdfjs-dist/lib/pdf.worker";
import {
PdfLoader,
PdfHighlighter,
Tip,
Highlight,
Popup,
AreaHighlight,
setPdfWorker
} from "react-pdf-highlighter";
import Spinner from "./Spinner";
import Sidebar from "./Sidebar";
import testHighlights from "./test-highlights";
import type {
T_Highlight,
T_NewHighlight
} from "react-pdf-highlighter/src/types";
import "./style/App.css";
setPdfWorker(PDFWorker);
type Props = {};
type State = {
url: string,
highlights: Array<T_Highlight>
};
const getNextId = () => String(Math.random()).slice(2);
const parseIdFromHash = () =>
document.location.hash.slice("#highlight-".length);
const resetHash = () => {
document.location.hash = "";
};
const HighlightPopup = ({ comment }) =>
comment.text ? (
<div className="Highlight__popup">
{comment.emoji} {comment.text}
</div>
) : null;
const PRIMARY_PDF_URL = "https://arxiv.org/pdf/1708.08021.pdf";
const SECONDARY_PDF_URL = "https://arxiv.org/pdf/1604.02480.pdf";
const searchParams = new URLSearchParams(document.location.search);
const initialUrl = searchParams.get("url") || PRIMARY_PDF_URL;
class App extends Component<Props, State> {
state = {
url: initialUrl,
highlights: testHighlights[initialUrl]
? [...testHighlights[initialUrl]]
: []
};
state: State;
resetHighlights = () => {
this.setState({
highlights: []
});
};
toggleDocument = () => {
const newUrl =
this.state.url === PRIMARY_PDF_URL ? SECONDARY_PDF_URL : PRIMARY_PDF_URL;
this.setState({
url: newUrl,
highlights: testHighlights[newUrl] ? [...testHighlights[newUrl]] : []
});
};
scrollViewerTo = (highlight: any) => {};
scrollToHighlightFromHash = () => {
const highlight = this.getHighlightById(parseIdFromHash());
if (highlight) {
this.scrollViewerTo(highlight);
}
};
componentDidMount() {
window.addEventListener(
"hashchange",
this.scrollToHighlightFromHash,
false
);
}
getHighlightById(id: string) {
const { highlights } = this.state;
return highlights.find(highlight => highlight.id === id);
}
addHighlight(highlight: T_NewHighlight) {
const { highlights } = this.state;
console.log("Saving highlight", highlight);
this.setState({
highlights: [{ ...highlight, id: getNextId() }, ...highlights]
});
}
updateHighlight(highlightId: string, position: Object, content: Object) {
console.log("Updating highlight", highlightId, position, content);
this.setState({
highlights: this.state.highlights.map(h => {
const {
id,
position: originalPosition,
content: originalContent,
...rest
} = h;
return id === highlightId
? {
id,
position: { ...originalPosition, ...position },
content: { ...originalContent, ...content },
...rest
}
: h;
})
});
}
render() {
const { url, highlights } = this.state;
return (
<div className="App" style={{ display: "flex", height: "100vh" }}>
<Sidebar
highlights={highlights}
resetHighlights={this.resetHighlights}
toggleDocument={this.toggleDocument}
/>
<div
style={{
height: "100vh",
width: "75vw",
position: "relative"
}}
>
<PdfLoader url={url} beforeLoad={<Spinner />}>
{pdfDocument => (
<PdfHighlighter
pdfDocument={pdfDocument}
enableAreaSelection={event => event.altKey}
onScrollChange={resetHash}
// pdfScaleValue="page-width"
scrollRef={scrollTo => {
this.scrollViewerTo = scrollTo;
this.scrollToHighlightFromHash();
}}
onSelectionFinished={(
position,
content,
hideTipAndSelection,
transformSelection
) => (
<Tip
onOpen={transformSelection}
onConfirm={comment => {
this.addHighlight({ content, position, comment });
hideTipAndSelection();
}}
/>
)}
highlightTransform={(
highlight,
index,
setTip,
hideTip,
viewportToScaled,
screenshot,
isScrolledTo
) => {
const isTextHighlight = !Boolean(
highlight.content && highlight.content.image
);
const component = isTextHighlight ? (
<Highlight
isScrolledTo={isScrolledTo}
position={highlight.position}
comment={highlight.comment}
/>
) : (
<AreaHighlight
highlight={highlight}
onChange={boundingRect => {
this.updateHighlight(
highlight.id,
{ boundingRect: viewportToScaled(boundingRect) },
{ image: screenshot(boundingRect) }
);
}}
/>
);
return (
<Popup
popupContent={<HighlightPopup {...highlight} />}
onMouseOver={popupContent =>
setTip(highlight, highlight => popupContent)
}
onMouseOut={hideTip}
key={index}
children={component}
/>
);
}}
highlights={highlights}
/>
)}
</PdfLoader>
</div>
</div>
);
}
}
export default App;
<<test-highlights.js >>
const testHighlights =async () => {
const res= await fetch('http://127.0.0.1:5000/jsonapi')
const data =await res.json()
console.log(data)
this.state.testHighlights = data
return testHighlights;
}
export default testHighlights;
You can't assign state like this
this.state.testHighlights = data
You must use this.setState function to do it
this.setState({ testHighlights: data });
That is why your testHighlights state isn't what you was expected
I have this function where i have to return/display the value of results, I'am using react native and couchDB as my database this code is inside of a flatlist. I have tried this one but it is not working. please help me with this one.
vacant (room) {
localNoteDb
.find({
selector: {
status: "vacant",
room_type: room
},
fields: ['_id', 'room_type', 'room_no' ,'price','status','user', 'updated_at', 'hour_status', 'price_per'],
use_index: nameIndex_status.status,
sort: [{status: 'asc'}]
})
.then(result => {
console.log('getListNoteFromDb', result)
let getLenght = result.doc
const results= Object.keys(result).length
console.log('value of results: ', results)
return(
<Text> {Object.keys(result).length}</Text>
);
})
}
Try this way
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount
useEffect(() => {
vacant(...);
});
const vacant (room) {
localNoteDb
.....
.....
.then(result => {
console.log('getListNoteFromDb', result)
let getLenght = result.doc
const results= Object.keys(result).length
setCount(results); <-- This way -->
});
}
return (
<Text> {count}</Text>
);
}
how to add css in such a way whenever i click and select on div the border and background colors of the div should be changed same goes for all for the selected and should be back to previous if deselected.
This is a seemingly stupid question, but I'm not a pro when it comes to css. I have created a multiple div for multiple selection of div, but the css file that came with it has completely changed the look of it and it looks different to my other controls - Is there a simple way of inheriting the look of another control?
codesanbox
I tried this way
const data = [
{
key: 1,
value: "four"
},
{
key: 2,
value: "fours"
}
];
export default function App() {
const initialState = data.map((item) => {
return { ...item, selected: false };
});
const [work, setWork] = React.useState(initialState);
const [state, setState] = React.useState();
const [selected, setSelected] = React.useState("");
console.log("work");
console.log(work);
console.log("work");
console.log("state");
console.log(state);
console.log("state");
React.useEffect(() => {
setState(
work.filter((person) => person.selected).map((person) => person.value)
);
setSelected(
work.filter((person) => person.selected).map((person) => person.value)
);
}, [work]);
const handleSelect = (value) => {
console.log("value", value);
const nextState = work.map((item) => {
if (item.value === value) {
return {
...item,
selected: !item.selected
};
}
return item;
});
setWork(nextState);
};
return (
<div className="parent">
{work.map((da) => (
<div
className={`child ${selected === da.value ? "selected" : ""}`}
onClick={() => handleSelect(da.value)}
>
{da.value}
</div>
))}
</div>
);
}
I've done slight modifications in the code.
Following code would help you get the desired results.
const handleSelect = (key) => {
const updatedItems = [];
work.forEach((item) => {
updatedItems.push ({
...item,
selected: item.key === key
});
});
setWork(updatedItems);
};
return (
<div className="parent">
{work.map((da) => (
<div
className={`child ${da.selected ? "selected" : ""}`}
onClick={() => handleSelect(da.key)}
>
{da.value}
</div>
))}
</div>
);
I am trying to load the data from exchangeratesapi but some how I cannot load the exchangerates's data!!
componentDidMount() {
this.setState({loading: true})
fetch("https://api.exchangeratesapi.io/latest")
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
loading: false,
currency: data,
})
})
}
render() {
var text = this.state.loading ? "loading..." : this.state.currency.BGN
return (
<div>
<p>{this.state.currency.RON}</p>
</div>
)
}
I have try on of the dumbest way to load the data.
omponentDidMount() {
this.setState({loading: true})
fetch("https://api.exchangeratesapi.io/latest")
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
loading: false,
currency: data,
bulgaria:data.rates.BGN,
})
})
}
And inside of render
var text = this.state.loading ? "loading..." : this.state.currency.bulgaria
But I believe there got a to be a better way to do this.
You are trying to access the property directly from currency however, it exists in rates.
This is incorrect:
{this.state.currency.RON}
It should be:
{this.state.currency.rates.RON}
Similarly, the variable text you created is not used anywhere. IMHO it should be like this:
render() {
const {loading, currency} = this.state;
console.log(currency); //only for debugging
return (
{ loading? 'Loading...' : (
<div>
<p>{currency.rates.RON}</p>
</div>)
}
)
}
I have got series of data that contains some objects in one array(json file) and it will be shown by react.
Here is my code:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: [],
library:null,
perPage: 20,
currentPage: 1,
maxPage: null,
filter: ""
};
}
componentDidMount() {
fetch('/json.bc')
// Here I want to get the length of my respose
.then(response => response.text())
.then(text => {
var Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(state => ({
...state,
data: Maindata
}), () => {
this.reorganiseLibrary()
})
}).catch(error => console.error(error))
}
reorganiseLibrary = () => {
const { filter, perPage , data } = this.state;
let library = data;
if (filter !== "") {
library = library.filter(item =>
item.hotelinfo.hotelsearch.realname.toLowerCase().includes(filter)
);
}
library = _.chunk(library, perPage);
this.setState({
library,
currentPage: 1,
maxPage: library.length === 0 ? 1 : library.length
});
};
// Previous Page
previousPage = () =>
this.setState(prevState => ({
currentPage: prevState.currentPage - 1
}));
// Next Page
nextPage = () =>
this.setState(prevState => ({
currentPage: prevState.currentPage + 1
}));
// handle filter
handleFilter = evt =>
this.setState(
{
filter: evt.target.value.toLowerCase()
},
() => {
this.reorganiseLibrary();
}
);
// handle per page
handlePerPage = (evt) =>
this.setState({
perPage: evt.target.value
}, () => this.reorganiseLibrary());
// handle render of library
renderLibrary = () => {
const { library, currentPage } = this.state;
if (!library || (library && library.length === 0)) {
return <div class="tltnodata">no result!</div>;
}
return library[currentPage - 1].map((item, i) => (
<input type="hidden" value={item.hotelinfo.hotelsearch.hotelid} name="hotelid"/>
));
};
render() {
const { library, currentPage, perPage, maxPage } = this.state;
return (
<div className="Main-wrapper">
<div class="filter_hotelname"><input value={this.state.filter} onChange={this.handleFilter} class="hotelName" /></div>
<div class="countHotel"> <span class="numbersearch"></span> // Here I want two show the count of items </div>
<div className="wrapper-data">
{this.renderLibrary()}
</div>
<div id="page-numbers">
<div class="nexprev">
{currentPage !== 1 && (
<button onClick={this.previousPage}><span class="fa-backward"></span></button>
)}
</div>
<div className="data_page-info">
{this.state.currentPage} از {this.state.maxPage}
</div>
<div class="nexprev">
{(currentPage < maxPage) && (
<button onClick={this.nextPage}><span class="fa-forward"></span></button>
)}
</div>
</div>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('Result'));
I want to find the length of response from a request with fetch. Also I want to know how to find the count of items that will be shown by renderLibrary . For example in json.bc we have 4 objects I want to show 4 in numbersearch span.
Using Fetch API you can find json response item length by running below code snippet. I have also added comment in code as well.
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
//below method return promise based response by converting stream object to json
return response.json();
}).then(json => {
//Once succcessful callback return you can find length of number of item
console.log(json);
alert("Number of item:"+json.length)
})
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
//below method return promise based response by converting stream object to json
return response.json();
}).then(json => {
//Once succcessful callback return you can find length of number of item
alert(json.length)
})
You can use the length of the data array from the state to distinguish the number of items.
Since arrays start at 0, you will need to increment the count by one. Here's an example snippet below that you can use in your code sample.
<div class="countHotel"><span class="numbersearch">{this.state.data && this.state.data.length + 1}</span></div>