1

I want to join all the names by using space

 const { author} = this.props;
        const authors= author.map((e, i) =>
            <div className="ck12 o6 b4" key={i}>
                <div className="authorlist">
                    <h4>{e.name}</h4>

The code looks like this. JohnTomJack I want John Tom Jack. I added e.name.join(" ") but code giving error join is not a function. I try how to render react components by using map and join but I could not.

1
  • Can you reproduce your problem in the code snippet? Commented May 11, 2018 at 7:35

1 Answer 1

9

Good morning sir,

The function join is only applicable to an Array. Learn more about it here: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/join

THis function will join all the elements (in most of the cases, strings) from the array to a single string.

For your specific case since the author name is inside an object with the property name, you could do the following:

const authorNames = author.map(e => e.name).join(' ');
// authorNames will be now John Tom Jack

You will use the map method to transform that array to a new array containing only strings. Then you can join those strings with the join function.

// Example class component
class Thingy extends React.Component {
  render() {
    const names = [{ name: 'John'}, {name: 'Doe'}, {name: 'Snow'}];
    console.log('names', names);
    return (
      <div>
        <div>{names.map(e => e.name).join(' ')}</div>
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Thingy />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.