Render HTML from a json string in react - javascript

I'm trying to render an HTML object from a JSON string that I'm receiving from an API. I'm able to get the string to render to HTML successfully but it shows the entire JSON string. I'm only looking to get specific values (Phone, Name, Id.) What would be the best way for me to extract specific values from my JSON array and format it in HTML? I'm referring to records by state but I'm unable to get any sub-value of record in the render process.
class menuScreen extends React.Component {
constructor(props) {
super(props)
const data = store.getState();
this.state = {
username: '',
messages: data.messages
}
}
handleSearch(e) {
this.setState({username: e.target.value})
}
handleChange(evt) {
this.setState({
username: evt.target.value.substr(0, 100)
});
}
onLinkClicked() {
var conn = new jsforce.Connection({serverUrl: 'https://cs63.salesforce.com', accessToken: sessionStorage.getItem('token')})
var parent = this.state.username
//console.log(this.state.username)
conn.sobject("Contact").find({
LastName: {
$like: parent
}
}, 'Id, Name, Phone'
).sort('-CreatedDate Name').
limit(5).skip(10).execute(function(err, records) {
if (err) {
return console.error(err);
}
for (var i = 0; i < records.length; i++) {
var record = (records[i]);
console.log("Name: " + record.Name); //these are the records I'm trying to render
console.log("Phone: " + record.Phone);
} this.setState({records : records})
}.bind(this));
}
render() {
return (
<div className='menubox' id='menubox'>
<div className='searchbar-container'>
<form onSubmit={e => e.preventDefault()}>
<input type='text' size='25' placeholder='Contact Last Name' onChange={this.handleChange.bind(this)} value={this.state.username}/>
<button type='submit' onClick={this.onLinkClicked.bind(this)}>
Search
</button>
</form>
</div>
<div>
<div dangerouslySetInnerHTML={ { __html: JSON.stringify(this.state.records) } }></div> //how can I show specific values, isntead of the entire string?
</div>
</div>
)
}
}
export default menuScreen;

JSON.parse your string into a JavaScript object. You can then do whatever processing you want on that object, such as removing fields you don't want, and then you can JSON.stringify it back into a JSON string which you can render.
Something like:
class BlahBlah extends React.Component {
constructor() {
//...some code...
this.processJson = this.processJson.bind(this)
}
//...a lot of code...
processJson(json) {
var object = JSON.parse(json)
var output = {}
//for every property you want
output[property] = object[property]
return JSON.stringify(output)
}
//...a lot more code...
render() {
return(
//...even more code...
<div dangerouslySetInnerHTML={ { __html: this.processJson(this.state.records) } }></div>
//...and yet more code.
)
}
}

You can run a map function and output the JSX for each item.
class menuScreen extends React.Component {
constructor(props) {
super(props)
const data = store.getState();
this.state = {
username: '',
messages: data.messages,
records: [],
};
}
render() {
return (
<div>
{this.state.records.map(record => (
<div>{record.attributes.name} {record.attributes.phone} {record.whatever}</div>
)}
</div>
);
}
}
Keep in mind, if you want a more complex HTML structure within map function, you'll have to wrap it in a single DOM node.
The full file would look like:
render() {
return (
<div className='menubox' id='menubox'>
<div className='searchbar-container'>
<form onSubmit={e => e.preventDefault()}>
<input type='text' size='25' placeholder='Contact Last Name' onChange={this.handleChange.bind(this)} value={this.state.username}/>
<button type='submit' onClick={this.onLinkClicked.bind(this)}>
Search
</button>
</form>
</div>
<div>
{this.state.records.map(record => (
<div>{record.attributes.name} {record.attributes.phone}</div>
)}
</div>
</div>
);
}

You could create a separate render method that will render your records like so:
renderRecords(records) {
return records.map(r => <div> r.Name, r.Phone</div>);
}
And then call the method inside your render method, instead of using dangerouslySetInnerHTML, like so
render() {
return (
<div className='menubox' id='menubox'>
<div className='searchbar-container'>
<form onSubmit={e => e.preventDefault()}>
<input type='text' size='25' placeholder='Contact Last Name' onChange={this.handleChange.bind(this)} value={this.state.username}/>
<button type='submit' onClick={this.onLinkClicked.bind(this)}>
Search
</button>
</form>
</div>
<div>
<div>{ this.renderRecords() }</div>
</div>
</div>
)
}

Related

Issue with unique key props for child elements

I have a generic Todo List built in React. Each task from user input is stored in tasks array declared in parent component <ReactTodoApp />. Tasks are rendered in child component <TodoList />. A unique key is assigned to each task in DOM element <label />. When inspecting dev tools unique ids are generating, however error is still present.
Would anyone know why I am still getting the "unique key prop" error?
Link to working application: https://codesandbox.io/s/todo-list-34udn?file=/src/App.js
JS file:
import React, { Component } from "react";
import "./styles.css";
export default class ReactTodoApp extends Component {
constructor(props) {
super(props);
this.state = {
//container for new task
input: "",
tasks: []
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleChange(event) {
this.setState({ input: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
//condition for empty empty
if (!this.state.input) {
return;
}
//declare object to store
const newTask = {
input: this.state.input,
id: 1 + Math.random()
};
//request update to current tasks state
this.setState((state) => ({
tasks: state.tasks.concat(newTask),
input: ""
}));
}
//updater function to remove task
handleRemove(props) {
//create new task list
const newTasksList = this.state.tasks;
//remove selected item from new task list
newTasksList.splice(props, 1);
//update state for tasks
this.setState({ tasks: newTasksList });
}
render() {
return (
<div>
<h1>React Todo</h1>
<form onSubmit={this.handleSubmit} className="add-item">
<input
type="text"
value={this.state.input}
onChange={this.handleChange}
className="add-item__input"
placeholder="new item"
/>
<button type="submit" className="submit">
add item
</button>
</form>
<TodoList tasks={this.state.tasks} handleRemove={this.handleRemove} />
</div>
);
}
}
class TodoList extends React.Component {
render() {
return (
<div className="list-container">
{this.props.tasks.map((task) => (
<label keys={task.id} className="item-container">
<input type="checkbox" />
<p className="item__text">{task.input}</p>
<button onClick={this.props.handleRemove} className="remove-button">
x
</button>
<span className="custom-checkbox" />
</label>
))}
</div>
);
}
}
Just change keys={task.id} to key={task.id}

Conditional rendering on select

I am pretty new to the wonderful world of React.
I have two inputs passing data through from an API that renders a list of options. And I want to send the selected inputs from those options back to the parent in the input fields to display for another search.
I have tried passing state down to them and render them them optionally with both a ternary and an if else statement in the "SearchCityList" component in several ways but I either get both lists rendered and they would have to choose between one list that is doubled to put in each input field or it only puts the selected value in one input. Would appreciate any & all suggestions Thanks!
class Form extends Component {
state = {
showComponent: false,
showComponent2: false,
};
// open/close control over SearchCity component box
openSearch = () => {
this.setState({ showComponent: true });
};
openSearch2 = () => {
this.setState({ showComponent2: true });
};
closeSearch = () => {
this.setState({
showComponent: false,
showComponent2: false
});
};
// Passed down cb function to get selected city search in selectCity component
GoingTo = (flights) => {
this.setState({ GoingTo: [flights] });
};
LeavingFrom = (flights) => {
this.setState({ LeavingFrom: [flights] });
};
render() {
return (
<div>
<form className="form-fields container">
<div className="inputs">
<h1>Search for a flight!</h1>
<div className="depart">
<input
onClick={this.openSearch}
className="flight-search"
placeholder="Leaving From"
value={this.state.LeavingFrom}
></input>
<input type="date"></input>
</div>
<div className="Returning">
<input
onClick={this.openSearch2}
className="flight-search"
placeholder="Going To "
value={this.state.GoingTo}
></input>
<input type="date" placeholder="Returning"></input>
</div>
</div>
<button>Check Flights!</button>
</form>
{this.state.showComponent || this.state.showComponent2 ? (
<SearchCity
openSearch={this.openSearch}
openSearch2={this.openSearch2}
flightSearch={this.state.flightSearch}
closeSearch={this.closeSearch}
GoingTo={this.GoingTo}
LeavingFrom={this.LeavingFrom}
onSearchSubmission={this.onSearchSubmission}
closeSearch={this.closeSearch}
/>
) : null}
</div>
);
}
}
export default Form;
class SearchCity extends Component {
state = {
LeavingFrom: "",
GoingTo: "",
search: "",
flightSearch: [],
};
// Search submission / api call
onSearchSubmission = async (search) => {
const response = await Axios.get(
{
headers: {
"
useQueryString: true,
},
}
);
// set New state with array of searched flight data sent to searchCity component
const flightSearch = this.setState({ flightSearch: response.data.Places });
};
// Callback function to send search/input to parent "Form" component
submitSearch = (e) => {
e.preventDefault();
this.onSearchSubmission(this.state.search);
};
// closeSearch callback function sent from Form component to close pop up search box when X is pressed
closeSearch = () => {
this.props.closeSearch();
};
render() {
return (
<div className="container search-list">
<form onChange={this.submitSearch}>
<i className="fas fa-times close-btn" onClick={this.closeSearch}></i>
<input
onChange={(e) => this.setState({ search: e.target.value })} //query-search api
value={this.state.search}
className="search-input"
type="text"
placeholder="Search Locations"
></input>
<div className="search-scroll">
<SearchCityList
openSearch={this.props.openSearch}
openSearch2={this.props.openSearch2}
LeavingFrom={this.props.LeavingFrom}
GoingTo={this.props.GoingTo}
flightSearch={this.state.flightSearch}
/>
</div>
</form>
</div>
);
}
}
export default SearchCity;
function SearchCityList({ flightSearch, LeavingFrom, GoingTo }) {
const renderList = flightSearch.map((flights) => {
return (
<div>
<SelectCityLeaving LeavingFrom={LeavingFrom} flights={flights} />
<SelectCityGoing GoingTo={GoingTo} flights={flights} />
</div>
);
});
return <div>{renderList}</div>;
}
export default SearchCityList;
First of all, when dealing with state, make sure you initialize in the constructor and also ensure you bind your handlers to this component instance as this will refer to something else in the handlers if you don't and you won't be able to call this.setState().
constructor(props) {
super(props); // important
state = {
// your state
};
// make sure to bind the handlers so `this` refers to the
// component like so
this.openSearch = this.openSearch.bind(this);
}

Passing ref up to parent in react

I have a little app that has an input and based on the search value, displays weather for a particular city. I'm stuck at a certain point though. The idea is that once you search a city, it hides the text input and search button and displays some weather info and another search button to search a new city. My issue is that I want to focus on the search box once I click to search again. I hope that makes sense. I read that the ideal way to do this is with refs. I wired it up like such:
class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.city = React.createRef();
}
componentDidMount() {
this.props.passRefUpward(this.city);
this.city.current.focus();
}
render() {
if (this.props.isOpen) {
return (
<div className={style.weatherForm}>
<form action='/' method='GET'>
<input
ref={this.city}
onChange={this.props.updateInputValue}
type='text'
placeholder='Search city'
/>
<input
onClick={e => this.props.getWeather(e)}
type='submit'
value='Search'
/>
</form>
</div>
)
} else {
return (
<div className={style.resetButton}>
<p>Seach another city?</p>
<button
onClick={this.props.resetSearch}>Search
</button>
</div>
);
}
}
}
With this I can pass that ref up to the parent to use in my search by using this.state.myRefs.current.value; It works great, but when I try to reference this.state.myRefs.current in a different function to use .focus(), it returns null.
resetSearch = () => {
console.log(this.state.myRefs.current); // <- returns null
this.setState({
isOpen: !this.state.isOpen,
details: [],
video: []
});
}
Is this because I'm hiding and showing different components based on the search click? I've read numerous posts on SO, but I still can't crack this. Any help is appreciated. I'll include the full code below. To see it in full here is the git repo: https://github.com/DanDeller/tinyWeather/blob/master/src/components/WeatherMain.js
class Weather extends React.Component {
constructor(props) {
super(props);
this.state = {
recentCities: [],
details: [],
isOpen: true,
myRefs: '',
video: '',
city: ''
};
this.updateInputValue = this.updateInputValue.bind(this);
this.getRefsFromChild = this.getRefsFromChild.bind(this);
this.resetSearch = this.resetSearch.bind(this);
this.getWeather = this.getWeather.bind(this);
}
updateInputValue = (e) => {
...
}
resetSearch = () => {
console.log(this.state.myRefs.current);
this.setState({
isOpen: !this.state.isOpen,
details: [],
video: []
});
}
getWeather = (e) => {
...
}
getRefsFromChild = (childRefs) => {
...
}
render() {
return (
<section className={style.container}>
<div className={style.weatherMain + ' ' + style.bodyText}>
<video key={this.state.video} className={style.video} loop autoPlay muted>
<source src={this.state.video} type="video/mp4">
</source>
Your browser does not support the video tag.
</video>
<div className={style.hold}>
<div className={style.weatherLeft}>
<WeatherForm
updateInputValue={this.updateInputValue}
getWeather={this.getWeather}
passRefUpward={this.getRefsFromChild}
resetSearch={this.resetSearch}
isOpen={this.state.isOpen}
/>
<WeatherList
details={this.state.details}
city={this.state.city}
isOpen={this.state.isOpen}
/>
</div>
<div className={style.weatherRight}>
<Sidebar
recentCities={this.state.recentCities}
/>
</div>
<div className={style.clear}></div>
</div>
</div>
</section>
);
}
}
class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.city = React.createRef();
}
componentDidMount() {
this.props.passRefUpward(this.city);
this.city.current.focus();
}
render() {
if (this.props.isOpen) {
return (
<div className={style.weatherForm}>
<form action='/' method='GET'>
<input
ref={this.city}
onChange={this.props.updateInputValue}
type='text'
placeholder='Search city'
/>
<input
onClick={e => this.props.getWeather(e)}
type='submit'
value='Search'
/>
</form>
</div>
)
} else {
return (
<div className={style.resetButton}>
<p>Seach another city?</p>
<button
onClick={this.props.resetSearch}>Search
</button>
</div>
);
}
}
}
export default Weather;
You try to achieve unmounted component from DOM, because of this you can not catch the reference. If you put this code your instead of render function of WeatherForm component, you can catch the reference. Because i just hide it, not remove from DOM.
render() {
return (
<div>
<div className={style.weatherForm}
style={this.props.isOpen ? {visibility:"initial"} :{visibility:"hidden"}}>
<form action='/' method='GET'>
<input
ref={this.city}
onChange={this.props.updateInputValue}
type='text'
placeholder='Search city'
/>
<input
onClick={e => this.props.getWeather(e)}
type='submit'
value='Search'
/>
</form>
</div>
<div className={style.resetButton} style={this.props.isOpen ? {visibility:"hidden"} :{visibility:"initial"}}>
<p>Seach another city?</p>
<button
onClick={this.props.resetSearch}>Search
</button>
</div>
</div>
)
}
console.log(this.state.myRefs.current) returns null , because it's a reference to an input dom element which does not exists as currently Weather form is displaying Search another city along with a reset button.
In reset function state changes, which results in change of prop isOpen for WeatherForm component. Now, screen would be displaying the input field along with search button.
After component is updated ComponentDidUpdate lifecycle method is called.
Please add ComponentDidUpdate lifecycle method in WeatherForm and add ,
this.city.current.focus() in the body of method.
There is no need to pass reference of a dom element to the parent element as it is not consider as a good practise.
Edit 1 :-
Need to set input field in focus only if prop ( isOpen ) is true as we will get reference to the input field only if its mounted.
ComponentDidUpdate(){
if(this props.isOpen)
this.city.current.focus
}
Link to Lifecycle method :-
https://reactjs.org/docs/react-component.html#componentdidupdate
Hope this helps,
Cheers !!

how to get new lines "\n" from string also reflected on the paragraph element

I have this Note element in React to show saved strings input by user from a text area. Somehow, new line is not reflected and replaced by space.
I have checked the strings before it's mapped to paragraph, the string still have the new lines characteres. But when it's mapped to paragraph, the new lines are replaced by spaces.
How to make the new lines remain reflected on the new created paragraph elements? Below is my code.
class Note extends React.Component {
render() {
return (
this.props.notes.map((note, index) =>
<div className="note-important" key={index}>
<p>{note}</p>
</div>
)
);
}
}
class NoteAndDone extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
notes: [],
}
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
input: e.target.value
})
}
handleClick(e) {
let input = document.getElementById('textarea-note').value;
if (input && !/^\s*$/.test(input)) {
this.setState({
notes: this.state.notes.concat(this.state.input)
});
}
}
render() {
return (
<div className="NoteAndDone">
<div className="Title">Note</div>
<textarea id="textarea-note" onChange={this.handleChange} placeholder='Note important things here...' />
<div className="button-save-container">
<button className="btn btn-primary" id="button-save-note" onClick={this.handleClick}>Save</button>
</div>
<Note notes={this.state.notes}/>
</div>
);
}
}
perhaps you could make the following updates to your Note component?
class Note extends React.Component {
render() {
return (
this.props.notes.map((note, index) =>
<div className="note-important" key={index}>
{ /* split the note string by \n, filter non-empty lines, and map each resulting line to it's own paragraph element */ }
{ note.split('\n').filterline => !!line).map(line => <p>
{{ line }}</p>) }
</div>
)
);
}
}
Perhaps you should replace the newlines with breaks?
Simply replace line 7 with:
<p>{note.replace("\n","<br />","g")}</p>
Though there may be a good reason why you chose not to do this...

Getting value from react component

I have a component InputArea with state = {input: ''}
Then I map several of these components in a container and write them in state = {inputAreas: []}
Now, how can I get inputs in the container? Logging this.state.inputAreas[0] returns object like this:
{$$typeof: Symbol(react.element), type: ƒ, key: "1", ref: null, props:
{…}, …}
In elements it shows like this:
<input type="text" class="form-control" name="input" value="abc">
Using this.state.prefooterArea[0].value gives undefined.
I also tried passing input from component to container as props, but it says getInput is not a function. From what I understood it has something to do with the fact I used map in the container. I can't use redux in this project.
Code of component
class PrefooterAreaInput extends Component {
state = {
input: ''
}
textChangedHandler = (event) => {
let newState = {};
newState[event.target.name] = event.target.value;
this.setState(newState);
}
render() {
return (
<div>
<input
className="form-control"
type="text"
name="input"
value = {this.state.input}
onChange={this.textChangedHandler}
/>
</div>
)
}
}
Code of container
class DescriptionFrame extends Component {
state = {,
prefooterArea: [<PrefooterAreaInput key={1}/>]
};
addFooterInputHandler = event => {
event.preventDefault();
if (this.state.prefooterArea.length < prefooterInputFieldsMax) {
var newPrefooterArea = this.state.prefooterArea.map(
inputField => inputField
);
newPrefooterArea.push(
<PrefooterAreaInput key={this.state.prefooterArea.length + 1} />
);
this.setState({ prefooterArea: newPrefooterArea });
}
};
removeFooterInputHandler = event => {
event.preventDefault();
if (this.state.prefooterArea.length > 1) {
var newPrefooterArea = this.state.prefooterArea.map(
inputField => inputField
);
newPrefooterArea.splice(newPrefooterArea.length - 1);
this.setState({ prefooterArea: newPrefooterArea });
}
render() {
// want to get this.state.prefooterArea[0]'s value
return (
<div>
{this.state.prefooterArea}
<a
className="nav-link"
href=""
onClick={this.addFooterInputHandler}
>
Add More
</a>
<a
className="nav-link"
href=""
onClick={this.removeFooterInputHandler}
>
Remove Last
</a>
</div>
);
}
}
Figured it out. This caused problem.
prefooterArea: [<PrefooterAreaInput key={1}/>]
I should have added that initial PrefooterAreaInput with lifecycle method instead. With that I was able to pass state just fine.
Are you trying to achieve something like this ?
child component :
export default class InputBox extends React.Component {
render() {
return (
<input onChange={event => this.props.onChange(event.target.value)} />
);
}}
parent component :
import InputBox from './InputBox';
class FilterBar extends React.Component {
constructor(props) {
super(props);
this.state = {
inputs: "" //get input value from state this input
};
this.updateFilters = this.updateFilters.bind(this);
}
updateFilters(i) {
this.setState({ inputs: i }); // this will print whatever input you type
}
render() {
return (
<div>
<InputBox onChange={(i) => this.updateFilters(i)} />
</div>
);
}
}

Categories

Resources