I want to create something like below in ReactJS but i can't figure out how and I most definitly don't want to use DangerouslySetInnerHTML. It's just a stupid example but i hope it makes clear what i want. Thanks for helping me out!
var page = {
title: <ReactTitle title={this.props.page.name} />
name: "Me myself and I"
};
var ReactTitle = React.createClass({
render: function(){
return (
<h1>{this.props.title}
);
}
})
var NewPage = React.createClass({
render: function(){
return (
<div className="row">
{this.props.page.title}
<div className="page-header"><h1>{this.props.page.name}</h1></div>
</div>
);
}
})
React.render(
<NewPage page={page} />
);
You can use React.createElement, like so
var page = {
title: React.createElement(ReactTitle, {title: "My awesome Title"}),
name: "Me myself and I"
};
Example
But in my opinion better use ReactTitle inside NewPage, like so
<div className="row">
<ReactTitle title={this.props.page.title} />
<div className="page-header"><h1>{this.props.page.name}</h1></div>
</div>
Example
My solution, with thanks to #Alexander
//Example
var page1 = {
title: [
React.createElement("h1", "", "This is my page title");
React.createElement("div", {className:"page-header"}, "This is the header of page 1");
],
name: "Me myself and I"
};
//So page2, which is slidely different:
//Example
var page2 = {
title: [
React.createElement("h2", {className:"h2"}, "Title part",
React.createElement("span", {className:"silent"}, "Silent part of page title")
),
React.createElement("div", {className:"page-header"}, "This is the header of page 2");
],
name: "Me myself and I"
};
Related
The images are not showing on the webpage, and I have been unable to figure out the problem.
here's my code. I had even tried using images locally on my computer, still the same.
import MeetupList from "../components/layout/meetups/meetupList";
const DATA = [
{
id: 'm1',
title: 'This is a first meetup',
image: 'https://unsplash.com/photos/nSY9XBCk58Y',
address: 'Meetupstreet 5, 12345 Meetup City',
description:
'This is a first, amazing meetup which you definitely should not miss. It will be a lot of fun!',
},
{
id: 'm2',
title: 'This is a second meetup',
image: 'https://unsplash.com/photos/nSY9XBCk58Y',
address: 'Meetupstreet 5, 12345 Meetup City',
description:
'This is a first, amazing meetup which you definitely should not miss. It will be a lot of fun!',
},
];
function AllMeetUpsPage(){
return <section>
<h1>All Meetups</h1>
<MeetupList meetups={DUMMY_DATA}/>
</section>
}
export default AllMeetUpsPage
#MeetupList component
import classes from './meetupList.module.css'
function MeetUpList(props){
return <ul className={classes.list}>
{props.meetups.map(meetup =>
<meetupItem key={meetup.id} id={meetup.id}
image={meetup.image}
title={meetup.title}
address={meetup.address}
description={meetup.description} />)}
</ul>
}
export default MeetUpList
export const TEST = () => {
const ImageData = [
{
src: "img-path",
alt: "this is x",
},
{
src: "img-path",
alt: "this is x",
},
{
src: "img-path",
alt: "this is x",
},
{
src: "img-path",
alt: "this is x",
},
];
return (
<div>
{ImageData.map((properties) => (
<img {...properties} />
))}
</div>
);
};
This is one way. You probably can't do {...properties} when you include description etc.
const MeetupList=({meetups})=>{
return(
<>
{
meetups.map((item,index)=>{
const[id,title,image,address,description]=item;
<>
<p>{id}</p>
<p>{title}</p>
//local image
<img src={require("path")}/>
//http images
<img src={image}/>
<p>{address}</p>
<p>{description}</p>
</>
})
}
</>
)
}
In order to load local images to your React.js application, you need to add require parameter in media sections.
I saw some questions speaking about similar issues but somehow I still do not manage to solve my issue so here I am asking for your kind help. I am pretty new to React and would like to send a function from a Parent to a child and then use it from the Child but somehow when I want to use it it says
Uncaught TypeError: Cannot read property 'props' of undefined"
Edited Code after first answers were helping:
var Menu = React.createClass({
links : [
{key : 1, name : "help", click : this.props.changePageHelp}
],
render : function() {
var menuItem = this.links.map(function(link){
return (
<li key={link.key} className="menu-help menu-link" onClick={link.click}>{link.name}</li>
)
});
return (
<ul>
{menuItem}
</ul>
)
}
});
var Admin = React.createClass ({
_changePageHelp : function() {
console.log('help');
},
render : function () {
return (
<div>
<div id="menu-admin"><Menu changePageHelp={this._changePageHelp.bind(this)} /></div>
</div>
)
}
});
ReactDOM.render(<Admin />, document.getElementById('admin'));
Pass a value from Menu function and recieve it in the changePageHelp function and it works.
var Menu = React.createClass({
render : function() {
return (
<div>
{this.props.changePageHelp('Hello')}
</div>
)
}
});
var Admin = React.createClass ({
_changePageHelp : function(help) {
return help;
},
render : function () {
return (
<div>
<div id="menu-admin"><Menu changePageHelp={this._changePageHelp.bind(this)} /></div>
</div>
)
}
});
ReactDOM.render(<Admin />, document.getElementById('admin'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="admin"></div>
For performance reasons, you should avoid using bind or arrow functions in JSX props. This is because a copy of the event handling function is created for every instance generated by the map() function. This is explained here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
To avoid this you can pull the repeated section into its own component. Here is a demo: http://codepen.io/PiotrBerebecki/pen/EgvjmZ The console.log() call in your parent component receives now the name of the link. You could use it for example in React Router.
var Admin = React.createClass ({
_changePageHelp : function(name) {
console.log(name);
},
render : function () {
return (
<div>
<div id="menu-admin">
<Menu changePageHelp={this._changePageHelp} />
</div>
</div>
);
}
});
var Menu = React.createClass({
getDefaultProps: function() {
return {
links: [
{key: 1, name: 'help'},
{key: 2, name: 'about'},
{key: 3, name: 'contact'}
]
};
},
render: function() {
var menuItem = this.props.links.map((link) => {
return (
<MenuItem key={link.key}
name={link.name}
changePageHelp={this.props.changePageHelp}
className="menu-help menu-link" />
);
});
return (
<ul>
{menuItem}
</ul>
);
}
});
var MenuItem = React.createClass ({
handleClick: function() {
this.props.changePageHelp(this.props.name);
},
render : function () {
return (
<li onClick={this.handleClick}>
Click me to console log in Admin component <b>{this.props.name}</b>
</li>
);
}
});
ReactDOM.render(<Admin />, document.getElementById('admin'));
I'm loading some JSON data using FETCH. I'm trying to add/create a simple filtering functionality on the content displayed.
I'm getting this error:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
Any idea what could be causing this error?
This my code so far:
let Table = React.createClass({
getInitialState: function(){
return {
accounts: [{
"product": "Fixed Saver",
"interestRate": 2.20,
"minimumDeposit": 500,
"interestType": "Fixed"
}],
searchString: ''
}
},
componentDidMount: function(){
fetch('http://localhost:8888/table/json/accounts.json')
.then(response => {
return response.json()
})
.then(json => {
this.setState({accounts: json})
});
},
handleChange: function(e){
this.setState({searchString:e.target.value});
},
render: function(){
var libraries,
libraries = this.state.accounts,
searchString = this.state.searchString.trim().toLowerCase();
if(searchString.length > 0){
libraries = libraries.filter(l => {
return l.name.toLowerCase().match( searchString );
});
}
return (
<div className="container">
<input type="text" value={this.state.searchString} onChange={this.handleChange} placeholder="Type here" />
<ul className="header clearfix">
<li>Product</li>
<li>Interest rate</li>
<li>Minimum deposit</li>
<li>Interest type</li>
</ul>
{libraries.map(l => {
return (
<div className="account clearfix" key={l.id}>
<div className="product">{l.product}</div>
<div>{l.interestRate} %</div>
<div>£ {l.minimumDeposit}</div>
<div>{l.interestType}</div>
</div>
)
})}
</div>
)
}
});
let App = React.createClass({
render: function(){
return(
<Table />
);
}
});
ReactDOM.render( <App />, document.getElementById('table') );
JSON
[
{
"id": 1,
"product": "Fixed Saver",
"interestRate": 2.20,
"minimumDeposit": 500,
"interestType": "Fixed"
},
{
"id": 2,
"product": "Fixed Saver",
"interestRate": 1.50,
"minimumDeposit": 0,
"interestType": "Tracker"
},
{
"id": 3,
"product": "Offset Saver",
"interestRate": 1.8,
"minimumDeposit": 1000,
"interestType": "Fixed"
}
]
Seem that you got the error from this line
libraries = libraries.filter(l => {
return l.name.toLowerCase().match( searchString );
});
Because of l.name is undefined. You can check again your JSON data. It doesn't have name attribute, seem that it is product.
You should not modify your state directly by: libraries = libraries.filter...
State should be updated by setState function.
In this case you should create temporary variable to display the results instead of directly use libraries variable.
I believe if your sample is worked, you only may search for the first time and next time the results will be only in your last search results, though.
http://jsfiddle.net/adamchenwei/3rt0930z/20/
I just trying to create an example to learn how state works in a list.
What I intent to do is to allow a particular value that got repeated in a list, to change, in ALL items in the list, by using state. For example, in this case, I want to change all the list item's name to 'lalala' when I run changeName of onClick.
However I have this warning (issue at fiddle version 11, resolved at version 15)
Any help on resolving it to achieve purpose above?
Actual Code
var items = [
{ name: 'Believe In Allah', link: 'https://www.quran.com' },
{ name: 'Prayer', link: 'https://www.quran.com' },
{ name: 'Zakat', link: 'https://www.quran.com' },
{ name: 'Fasting', link: 'https://www.quran.com' },
{ name: 'Hajj', link: 'https://www.quran.com' },
];
var ItemModule = React.createClass({
getInitialState: function() {
return { newName: this.props.name }
},
changeName() {
console.log('changed name');
this.setState({ newName: 'lalala' });
},
render() {
//<!-- <a className='button' href={this.props.link}>{this.props.name}</a> -->
return (
<li onClick={this.changeName}>
{this.state.newName}
</li>
);
}
});
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: [] }
},
render: function() {
var listItems = this.props.items.map(function(item) {
return (
<div>
<ItemModule
key={item.name}
name={item.name} />
</div>
);
});
return (
<div className='pure-menu'>
<h3>Islam Pillars</h3>
<ul>
{listItems}
</ul>
</div>
);
}
});
ReactDOM.render(<RepeatModule items={items} />,
document.getElementById('react-content'));
-UPDATE-
fiddle version 16
updated fidle, now there is issue with key, also, the onClick did not update the value for all the list item. Is there something wrong I did?
-UPDATE-
fiddle version 20
Now the only issue is change all the list item's name to 'lalala' when I run changeName of onClick.
remove the parenthesis from
onClick={this.changeName()},
so
onClick={this.changeName}
you want to call the function onClick, but you are calling it on render that way
I think you meant to do onClick={this.changeName}
In the way you have it you are calling the changeName function on render instead of on click.
I am starting to get involved in ReactJS, I am trying to pass to my tag a JSON object so then I can show it in the UI but it keeps saying that element is not found. Any help on this? Or why the props object is not having the JSON object? Thanks in advance
var CommentBox = React.createClass({
render: function() {
return (
<div className="img-container">
<img src="{this.props.placementImage}" />
</div>
);
}
});
var MP = [
{
id: "MP1001",
placementImage: "https://www.aexp-static.com/intl/uk/rwd/images/UKHP_CM_promo_3.png",
dts: "forever",
dte: "forever",
status: "",
isDefault: false
}
];
ReactDOM.render(
<CommentBox mp={MP}/>,
document.getElementById('content')
);
A couple things:
You're passing an array as the mp prop, but then attempting to access it like an object.
You need to remove the quotes from the <img> src attribute:
You need to access the actual mp prop
For reference, I've created a JSBin example from your code that fixes these issues: http://jsbin.com/bohoqa/edit?html,js,output
var CommentBox = React.createClass({
render: function() {
return (
<div className="img-container">
<img src={this.props.mp.placementImage} />
</div>
);
}
});
var MP = [
{
id: "MP1001",
placementImage: "https://www.aexp-static.com/intl/uk/rwd/images/UKHP_CM_promo_3.png",
dts: "forever",
dte: "forever",
status: "",
isDefault: false
}
];
ReactDOM.render(
<CommentBox mp={MP[0]}/>,
document.getElementById('content')
);
change
<img src="{this.props.placementImage}" />
to
<img src={this.props.mp[index].placementImage} />
You have to pass them as objects {} not "{}"
edit: I did not notice it was an array